How we change what others think, feel, believe and do
CHAPTER 5 : Naming
5.6 Naming functions
Functions perform actions (they 'do' things), which can usually be described with a verb:
Check(), Reset(), Find()
In a simple situation, what is being Checked, Reset or Found may be obvious, but in a program of any reasonable size a simple verb name is likely to be insufficient.
These 'actions' that functions typically 'do' are to 'things'. This can be put into practice by creating function names which use a verb to describe what is being 'done' in combination with a noun to describe the 'thing':
CheckWidget(), ResetParagraph(), FindPointer()
If a function performs several actions, then this scheme can be awkward to use, as you could end up with rather silly (but correct) names like:
However, a functionally cohesive function (see 7.2.2) which performs a single function allows easy and accurate use of the above verb-noun scheme.
In a complex situation, the noun may not be sufficient description for the 'thing'; in this case an adjective, or more, may be required to qualify it:
CheckPrimaryWidget(), ResetFirstParagraph(), FindFirstFreeMemoryPointer()
An extension to this naming scheme is, in appropriate cases, to make the whole function read better by adding a preposition to the name (ie. by, in, from, for, to, with, between, etc.):
CheckWidgetAgainst( StandardWidget ), ResetParagraphTo( ParaTemplate )
When a function returns a variable (other than a simple status return), it may be named by using variable-naming rules (see 5.8), rather than describing the action taken to derive that variable. Which of the following would you chose?
WidgetArea = WidgetWidth * FindHeight( Widget );
WidgetArea = WidgetWidth * WidgetHeight( Widget );
Particularly when used in expressions, the second alternative can be noticeably clearer. Functions should be named so that they will make sense to their caller.
Objections to using much more than a simple verb are usually along the lines that the length of the name is inconvenient, unnecessary and obscuring. It also takes more effort to create a good name. Against this must be set the clarity of purpose that a fuller name gives.
And the big