by shigemk2

当面は技術的なことしか書かない

97 Things Every Programmer Should Know 15 Coding with Reason

コードの論理を分かりやすくする術について。

  • Avoid using got statements, as they make remote sections highly interdependent.
  • Avoide using modifiable global variables, as they make all sections that use them dependent.
  • Each variable should have the smallest possible scope. For example, a local object can be declared right before its first usage.
  • Make objexts immutable whenever relevant.
  • Make the code readable by using spacing, both horizontal and vertical -e.g.,aligning related structures and using an empty line to separate two sections.
  • Make the code self-documenting by choosing descriptive (but relatively short) names for objects, types, functions, etc.
  • If you need a nested section, make it a function.
  • Make your functions short and focused on a single task. The old 24-line limit still applies. Although screen size and resolution have changed, nothing has changed in human cognition since the 1960s.
  • Functions should have few parameter (four is a good upper bound). This does not restrict the data communicated to functions: grouping related parameters into a single object localizes object invariants, which simplifies reasoning with respect to their coherence and consistency.
  • More generally, each unit of code, from a block to a library, should have a narrow interface. Less communication reduces the reasoning required. This means that getters that return internal state are a liability--don't ask an object for information to work with. Instead, ask the object to do the work with the information it already has. In other words, encapsulation is all --and only--about narrow interfaces.
  • In order to preserve class invariants, usage of setters should be discouraged. Setters tend to allow invariants that govern an object's stet to be broken.