|
|
20. Avoid long functions. Avoid deep nesting. Summary 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. Discussion ... 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. • ... Alexandrescu and Sutter in 'C++ Coding Standards: 101 Rules, Guidelines, and Best Practices' |
|
|
|
|
|
|