C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources]

Herb Sutter, Andrei Alexandrescu

نسخه متنی -صفحه : 521/ 117
نمايش فراداده

Discussion

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 understand 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 wondered which of the many

for s,

while s, or

if s it matched? Prefer better functional decomposition 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

    if s where an

    && condition will do.

  • Don't

    try

    too hard: Prefer automatic cleanup via destructors over

    TRy blocks (see Item 13).

  • 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).