Updated: 2025-08-28 Thu 17:03

Clean Code: Chapter 5 Notes

Table of Contents

Link to Chapter 4 | Link to Chapter 6

Chapter 5: Formatting

Vertical Formatting

  • Vertical openness (blank lines) separates concepts and improves readability.
  • Too much density makes code look like a muddle and harder to scan.

Vertical Density

  • Tightly related lines should appear vertically dense.
  • Avoid useless comments that interrupt association.
  • Example (bad):
public class ReporterConfig {
/**
* The class name of the reporter listener
*/
private String m_className;
  • Example (better):
public class ReporterConfig {
private String m_className;
private List<Property> m_properties = new ArrayList<>();

Vertical Distance

  • Related concepts should be kept close together to reduce scrolling and searching.
  • Local variables → as close to use as possible, usually at top of function.
  • Control variables → declared inside loop headers.
  • Instance variables → declared at the top of class (common Java convention).
for (Test each : tests) {
    count += each.countTestCases();
}
  • Dependent functions: caller above callee for natural top-down reading.
public Response makeResponse(...) {
    String pageName = getPageNameOrDefault(request, "FrontPage");
    loadPage(pageName, context);
    return makePageResponse(context);
}

private String getPageNameOrDefault(Request request, String defaultPageName) { ... }

Conceptual Affinity

  • Group functions with similar naming or shared purpose.
  • Example (JUnit assert methods):
static public void assertTrue(String message, boolean condition) { ... }
static public void assertTrue(boolean condition) { ... }
static public void assertFalse(String message, boolean condition) { ... }
static public void assertFalse(boolean condition) { ... }

Vertical Ordering

  • Organise code top down:
    • High-level concepts first (main logic).
    • Lower-level details later.
  • Readers can skim like a newspaper: important first, details last.
  • Contrast: C/C++ require declarations before use, Java does not.

Summary - vertical

  • Use vertical openness to separate concepts.
  • Use vertical density to group related ones.
  • Keep related variables, methods, and concepts close together.
  • Order code top down for natural readability.

Horizontal Formatting

Keep lines short. Most professional code naturally stays within ~45 characters, with ~80 as an upper bound. Lines beyond 100–120 characters are generally careless.

Avoid shrinking font or overly wide monitors to fit more code, readability > fitting more characters.

Example limit guideline:

// Good (short)
int sum = a + b + c;

// Bad (too long)
int sum = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q;

Horizontal Openness and Density

Use spaces to separate low-precedence operators (e.g., +, -, =) and improve readability.

Do not put spaces between function names and parentheses, they are closely related.

Example (Quadratic formula formatting):

return (-b + Math.sqrt(determinant)) / (2*a);

Separate arguments with spaces after commas to show distinct parameters.

Horizontal Alignment

Avoid aligning variable declarations or assignments in columns, it draws the eye to the wrong place.

Long aligned lists usually mean the class is too large and should be split.

Example (preferred unaligned):

// Prefer this:
private Socket socket;
private InputStream input;
private OutputStream output;

//instead of:
private Socket       socket;
private InputStream  input;
private OutputStream output;

Indentation

Indent according to scope hierarchy:

Classes → no indent

Methods → 1 level

Method bodies → 2 levels

Inner blocks → +1 for each nesting

Indentation makes scopes visually obvious; without it, code is hard to scan.

Avoid collapsing scopes onto one line, always use braces and proper indenting.

Dummy Scopes

Avoid dummy bodies in loops (e.g., empty while or for loops).

If unavoidable, place semicolon on its own indented line to make it visible.

while (dis.read(buf, 0, size) != -1)
    ;

Team Rules

Teams must agree on a single formatting style for consistency.

Use IDE formatters to enforce these rules across all files.

Consistent formatting builds trust and reduces mental load for readers.

Uncle Bob’s Formatting Rules (Example in CodeAnalyzer.java)

Short, clear methods with consistent spacing and indentation.

Use spaces around assignment and low-precedence operators, no space for high precedence operators.

Avoid deeply nested structures. Prefer clear, flat logic.

Example snippet:

private void measureLine(String line) {
  lineCount++;
  int lineSize = line.length();
  totalChars += lineSize;
  lineWidthHistogram.addLine(lineSize, lineCount);
  recordWidestLine(lineSize);
}