Thursday, February 11, 2010

The Cardinal Rule of Functions

Functions should be:
  • short
  • easy to understand
  • well-named
  • reusable
  • maintainable
All these desirable properties follow from obeying the Cardinal Rule of Functions.
One Function to a Function
That is, the code implementing a function should have one and only one task to do. Example tasks are:
  • Calculate: using primitive operators, calculate a value; this includes arithmetic, string operations, list building, and so on
  • Read or write: get data from or send data to files or users
  • Parse or format: convert text into structured data or construct text representations of structured data
  • Combine: apply several other functions to a set of arguments
  • Dispatch: decide which of several other functions to apply to a set of arguments
  • Iterate: repeatedly apply another function to a list of argument values
Notice that the latter tasks correspond to classic control structures (composition of function calls, conditional branching, and iteration). A symptom that the rule has been broken is when several of these control structures appear in one function. Another symptom is when you have trouble keeping a function to less than a dozen lines of code, and/or its lines to less than 72 characters.
Another good sign that the rule has been broken is difficulty naming the function clearly, or using names like scan-and-compress-and-print.

No comments:

Post a Comment