smalltalkpharopharo-5

How do we write if elseif elseif in pharo?


I have to check 3 conditons using the if elseif elseif. How can I do that in pharo. I did but am not sure since I did not find any such application in pharo.

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

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

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

Solution

  • You can choose different design (using polymorphism, lookup, ...) but that is pretty much the same for any OO language (for Smalltalk in particular, refer to this Refactoring if-chains in Smalltalk without class explosion ).

    In Smalltalk (and couple other languages such as Ruby) you have one extra option and that is class extension. You can design your own "if" statements that match well your particular domain and makes the code more obvious.

    E.g. in your given example, I could add a new method to the Number class called compareTo:lesser:equal:greater:, and then your code changes to

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

    This naturally depends on your particular domain, maybe in different case the wording would be different. E.g. in case of collections, there's col ifEmpty: [ ] ifNotEmpty: [ ], for nil there's ifNil:ifNotNil:, for detection detect:ifFound:ifNone:, for dictionaries at:ifPresent:ifAbsent:, etc.