Horizontal complexity

The horizontal complexity of source code pertains to both line length and to control nesting level. The Spartan programming methodology dictates minimization of horizontal complexity, and even place this objective higher than any other complexity metric minimization objective. This is because it is believed that horizontal scrolling is even more intellectually demanding then vertical scrolling. Further, it is believed that deep nested control is difficult to understand.

Specific techniques for reducing horizontal complexity include:

  1. Setting a fixed limit to line length. Traditionally, this limit is 80 characters. Longer lines are manually inspected in search for simplification opportunities. Lines are broken (and indented) as a last resort only if they resist all simplification attempts.
  2. Control simplification
  • A column should never span more than 80 characters. If you find that a column is too long, you should reduce its complexity, rather than break it into two distinct columns.
  • Simplify control flow by early exits from a method (via return) or from a loop (via break or continue).
  • Always omit the else of an if statement, if the main branch ends with a return statement or any other statement that does not let control carry through to the else branch.

For example, instead of

int abs(int x) {
  if (x < 0)
    return -x;
  else
    return x;
}

write

int abs(int x) {
  if (x < 0)
    return -x;
  return x;
}