2

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].
Friedrich
  • 2,211
  • 20
  • 42
ludo
  • 543
  • 3
  • 14
  • You could, naively, do something like `x < 25 ifTrue: [ ... ] ifFalse: [ . x = 25 ifTrue: [ ... ] ifFalse: [ . x > 25 ifTrue: [ ...] ifFalse: [ ... ] ] ]`. But you might want to have a look at [Refactoring if-chains in Smalltalk without class explosion](https://stackoverflow.com/questions/8113497/refactoring-if-chains-in-smalltalk-without-class-explosion). – lurker Jan 25 '18 at 12:15
  • If you were to think of your "do somethings" as actions (A1, A2, A3, ..., A6) then for `x = 25` you want A1, A4, A6, and for `x < 25` you want A2, A3, A6, and for `x > 25` you want A2, A4, A5. Regardless of language, I'd be examining my overall design to see if there's a refactoring. Otherwise, what you have there may be the most clear way to write it. The actions may need to be their own methods for clarity if they're complex actions in and of themselves. At it stands, with what you show so far, it's difficult to provide a definitive answer. – lurker Jan 25 '18 at 17:10

1 Answers1

3

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.

Peter Uhnak
  • 9,617
  • 5
  • 38
  • 51