我们如何在 pharo 中写 if elseif elseif?

How do we write if elseif elseif in pharo?

我必须使用 if elseif elseif 检查 3 个条件。我怎样才能在 pharo 中做到这一点。我做了但不确定,因为我在 pharo 中没有找到任何此类应用程序。

x = 25
ifTrue:[DoSomething]
ifFalse:[DoSomething else].

x < 25
ifTrue: [DoSomething]
ifFalse:[Domething else].

x > 25
ifTrue: [DoSomething ]
ifFalse:[DoSomething else].

您可以选择不同的设计(使用多态性、查找等),但这对于任何 OO 语言都几乎相同(特别是对于 Smalltalk,请参阅此 Refactoring if-chains in Smalltalk without class explosion)。

在 Smalltalk(以及其他一些语言,例如 Ruby)中,您有一个额外的选择,那就是 class 扩展。您可以设计自己的 "if" 语句来很好地匹配您的特定域并使代码更加明显。

例如在您给出的示例中,我可以向 Number class 添加一个名为 compareTo:lesser:equal:greater: 的新方法,然后您的代码更改为

x compareTo: 25
    lesser: [ do something ]
    equals: [ do something else ]
    greater: [ do something entirely different ]

这自然取决于您的特定领域,可能在不同的情况下措辞会有所不同。例如。对于集合,有 col ifEmpty: [ ] ifNotEmpty: [ ],对于 nil,有 ifNil:ifNotNil:,对于检测,有 detect:ifFound:ifNone:,对于字典,有 at:ifPresent:ifAbsent:,等等