21/08/2008

How should you name your methods and what should they return

Kent Beck's book on design patterns for smalltalk has some very useful rules about this. However, there are quite a few of them, and I have yet to commit them all to memory!

In the meantime, this section from Smalltalk By Example, seems really helpful. I am going to make sure any of my methods follow these rules - if only to avoid confusing myself further.


Often the method name will tell you what type of object will be returned. For example, method names that start with is will usually return a Boolean, true or false. For example,isEmpty,isNil. Messages that start with as will usually return the thing specified. For example,asSortedCollection sent to a collection will return aSortedCollection. The asNumber message sent to a string will return a number of the appropriate type. (However,asString is not implemented by numbers so you should use printString or displayString instead.)

Methods that add objects to collections, such as add: and at:put:, return the object that is added. Methods that remove single objects from collections, such as remove: and removeFirst, return the object that was removed. Because of this it's worth knowing about the yourself message. The following example illustrates how the use of yourself ensures that collection contains the list rather than the last object added


collection := List new 
add: thisObject;
add: thatObject;
yourself.


Consistency and predictability are great virtues, so when adding these types of methods to your own classes, follow the common usage patterns. Otherwise you'll confuse every programmer who looks at or uses your code.

No comments: