|20. Avoid long functions. Avoid deep nesting.|
Short is better than long, flat is better than deep: Excessively long functions and
nested code blocks are often caused by failing to give one function one cohesive re-
sponsibility (see Item 5), and both are usually solved by better refactoring.
Every function should be a coherent unit of work bearing a suggestive name (see
Item 5 and the Discussion in Item 70). When a function instead tries to merge such
small conceptual elements inside a long function body, it ends up doing too much.
Excessive straight-line function length and excessive block nesting depth (e.g., if,
for, while, and try blocks) are twin culprits that make functions more difficult to un-
derstand and maintain, and often needlessly so.
Each level of nesting adds intellectual overhead when reading code because you
need to maintain a mental stack (e.g., enter conditional, enter loop, enter try, enter
conditional, ...). Have you ever found a closing brace in someone's code and won-
dered which of the many fors, whiles, or ifs it matched? Prefer better functional de-
composition to help avoid forcing readers to keep as much context in mind at a time.
Exercise common sense and reasonableness: Limit the length and depth of your
functions. All of the following good advice also helps reduce length and nesting:
• Prefer cohesion: Give one function one responsibility (see Item 5).
• Don't repeat yourself: Prefer a named function over repeated similar code snippets.
• Prefer &&: Avoid nested consecutive ifs where an && condition will do.
• Don't try too hard: Prefer automatic cleanup via destructors over try blocks (see
• Prefer algorithms: They're flatter than loops, and often better (see Item 84).
• Don't switch on type tags. Prefer polymorphic functions (see Item 90).
|I would recommend either using tabs or spaces for your indentation, not both.|