Pattern: Method Name


Context

When creating a new method, the choice of a good selector name and the names of the parameters will promote the understanding of the method's purpose. It will also improve the readability of the method source and that of the methods which call it.

Solution

Choose a selector name which communicates what the method will do, not how it will do it. Avoid including any information about the implementation details.

Choose a name which will result in code that reads as a sentence.

Method names should always begin with a lowercase letter. If the name contains more than one word, then each subsequent word should begin with an uppercase letter. The exception to this is when a method takes more than one parameter - each component of the method name which follows a parameter should start with a lowercase letter.

The method name should read as a description of what to do with the parameters being passed eg. #at:put:. The parameter names should supply the type of the parameter and be of the form anInteger, aCharacter etc. We end up with the method which reads as a sentence:

#at: anInteger put: aCharacter

If there is more than one parameter of the same type, then the names should include further information to differentiate between them:

#from: startInteger to: stopInteger

In addition to the above guidelines, there is an informal convention for naming certain types of method.

Examples

open
asSortedCollection
includes: anObject
includesKey: aKey
at: anInteger put: aCharacter
from: startInteger to: stopInteger
associationAt: aKey ifAbsent: exceptionHandler
replaceFrom: start to: stop with: replacementElements startingAt: repStart

Related Patterns