Sign in
Log inSign up
"Clean Code" Book Summary, Part 4 - Formatting

"Clean Code" Book Summary, Part 4 - Formatting

Amir Anwar's photo
Amir Anwar
·Feb 20, 2017

How to format your code, so that it looks neat and readable?

This is what this chapter is about from "Clean Code" book

You can go to the start of the summary from here

Formatting:

  • Vertical Formatting: The file length in lines should be around the size of : 200-500 lines, this is not mandatory off course , but to be followed whenever possible.
  • Vertical Opennes: Methods should be separated by blank lines, also lines of code that differ in functionality should be separated by blank lines.

i.e: Opennes separates concepts

  • On the other hand: Vertical density (no blank lines) implies close link or assossiation.
  • Vertical distance: Concepts that are closely related should be kept vertically close to each other , e.g. methods of similar functions or of related function should be grouped and ordered together We want to avoid forcing our readers to hop around through our source files and classes.
  • Variable declarations inside methods should be as close as possible to their usages, e.g.:You declare a variable and use it directly in the following line of code.
      StringBuilder name = new StringBuilder();
      name.append("John");
  • Instance variable declarations should be in one location and most prefeably on the top of the class, or at least in the bottom.
  • Dependent Functions: If one function calls another, they should be vertically close, and the caller should be above the callee, if at all possible.
  • Conceptual Affinity: Certain bits of code want to be near other bits, The stronger that affinity, the less vertical distance there should be between them. Affinity might be caused because a group of functions perform a similar operation
  • Horizontal Formatting: lines should be of the sizes 100-120-max 200 characters.
  • Horizontal Opennes: The following example shows the use of spaces to add horizontal opennes to the code, Pay attention how we used the horizontal spaces:
        x = 1;
        X += 1;    
        count++;
    public void method(Argument arg, Argument2 arg2) {
        y = -b / (2\*a); y = c\*2 +y\*5;} //because multiplication is of higher precedance than addition
  • Indentation should be used to show different levels of hierarchy in the file.
  • Don't break the indentation rule even in the case of short If statements or short methods.

Continue to Part 5