21/08/2008

Using ifFalse: instead of ifTrue: as a guard clause

Smalltalk by Example advocates returning using an ifFalse test that returns self rather than an ifTrue test that then executes your code. For example doing this:


MyClass>>someMethod
(some condition) ifFalse: [^self]
self doThingOne.
self doThingTwo.
self doMoreLinesOfCode]

instead of:


MyClass>>someMethod
(some condition) ifTrue:
[self doThingOne.
self doThingTwo.
self doMoreLinesOfCode]


I don't think I understand this properly yet. There is something odd about asking, for example a list to do something, and for the return result to be the list. I am not sure how my coding would cope with that, i.e. rather than getting a failure message or something like that. More pondering required.

No comments: