Code Complete 2 – Steve McConnell – High-Quality Routines

I just love Steve McConnell’s classic book Code Complete 2, and I recommend it to everyone in the Software ‘world’ who’s willing to progress and sharpen his skills.

Other blog posts in this series:

Routines are used to:

  • reduce complexity
  • introduce an intermediate, understandable abstraction
  • avoid duplicate code
  • hide sequences
  • hide pointer operations
  • improve portability
  • simplify complicated boolean tests and
  • improve performance

Functional cohesion

Functional cohesion is when a function performs one and only one operation.

Cohesions that are considered to be less than ideal:

  • Sequential cohesion
    • exist when a routine contains operations that must be performed in a specific order, that share data from step to step.
  • Communicational cohesion
    • occurs when operations in a routine make use of the same data and aren’t related in any other way.
  • Temporal cohesion
    • occurs when operations are combined into a routine because they are all done at the same time. Think of temporal routines as organizers of other events.

Unacceptable kinds of cohesion:

  • Procedural cohesion
  • Logical cohesion
  • Coincidental cohesion

Good routine names and length

Research shows that the optimum average length for a variable name is 9-15 characters and 15-20 for a routine name.

To name the function use the description of the return value. In object-oriented languages, you don’t need to include the name of the object in the procedure name because the object itself is included in the call.

Avoid names like: document.PrintDocument().

A large percentage of routines in object-oriented programs will be accessor routines, which will be very short. From time to time, a complex algorithm will lead to a longer routine, and in those circumstances, the routine should be allowed to grow organically up to 100 – 200 lines.

Don’t write routines longer than about 200 lines.

How to use routine parameters

Interfaces between routines are some of the most error-prone areas of the program. Here are a few guidelines for minimizing interface problems:

  • Put parameters in input-modify-output order
  • If several routines use similar parameters, put the similar parameters in a consistent order
  • Use all the parameters
  • Put status or error variables last
  • Limit the number of a routine’s parameters to about seven

Psychological research has found that people generally cannot keep track of more than about seven chunks of information at once. (Miller 1956.)

The difference between function and procedure is that procedure doesn’t return a value.

You should use macro routines with care and only as a last resort.

Written by Nikola Brežnjak