Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring if-chains in Smalltalk without class explosion

As Smalltalk discourages the use of caseOf:, what aternatives exists to implement the following situation without class explosion?

self condition1
        ifTrue: [ self actionForCondition1 ]
        ifFalse: [ 
            self condition2
                ifTrue: [ self actionForCondition2 ]
                ifFalse: [ 
                    self condition3
                        ifTrue: [ self actionForCondition3 ]
                        ifFalse: [ ....  ] ] ]
like image 449
Juan Aguerre Avatar asked Nov 13 '11 17:11

Juan Aguerre


1 Answers

Depends on how your conditions exactly look like?

  • If your conditions are type tests

    anObject isKindOf: aClass
    

    you can dispatch on the class instead, that means you call an action method on anObject.

  • If your conditions are equality tests

    anObject = anotherObject
    

    you can use a dictionary with the object as key and the action as a block closure.

  • As a last restort and if nothing else helps you might want to rewrite the proposed code to avoid unnecessary nesting:

    self condition1
        ifTrue: [ ^ self actionForCondition1 ].
    self condition2
        ifTrue: [ ^ self actionForCondition2 ].
    self condition3
        ifTrue: [ ^ self actionForCondition3 ].
    ...
    
like image 54
Lukas Renggli Avatar answered Sep 22 '22 03:09

Lukas Renggli