Graduate Program KB

Clean Code

Chapter 5

The purpose of formatting

  • Code should be neat so it's readable and maintainable
  • A set of rules should govern how code is formatted
    • In a team environment, it ensures the coding style is consistent
    • There are automated tools that enforce this behaviour

Vertical formatting

  • According to several projects including Junit, FitNesse, etc., file sizes are typically about 200 lines long with 500 as the upper limit

  • This is a desirable rule, not necessarily strict. Though, smaller files are easier to understand

  • It can be related to a newspaper article

    • Read vertically
    • At the top there's a headline telling you what the story is about
    • The first paragraph gives a sypnosis
    • As you read further down, the details of the story unfold
  • In programming terms:

    • Our source file should have a simple name but is explanatory
    • The top of the file should contain functionality with high-level abstractions, they are easy to understand at a glance
    • As we read through the file, all the complex details and low-level abstraction concepts start to appear
  • Code should be vertically opened, that means separating different functionality with a new line

    • Add new lines between different sections for imports, classes, functions, etc.
    • Provides visual cues to the user that let them identify new concepts
  • If a section of the file looks dense, it's likely the density implies close association. Therefore, tightly coupled code should appear vertically dense

    • Notice how the unnecessary comments break the association of the variables, all the "noise" makes it more difficult to comprehend the concept
    public class ReporterConfig {
        /**
        * The class name of the reporter listener
        */
        private String m_className;
        /**
        * The properties of the reporter listener
        */
        private List<Property> m_properties = new ArrayList<Property>();
        public void addProperty(Property property) {
            m_properties.add(property);
        }
    
        ...
    }
    
  • Related functionality should appear closely to one another, it helps readers grasp the full idea of what some piece of code does

    • This includes closely related variables, or functions that depend on other functions
    • In some cases, a variable might be declared before a loop or function. In this case, declare it at the top of the block
    • Reduces the need to frantically search for code and understand the flow of execution

Horizontal formatting

  • Preferably, the amount of code on a single line should be short

    • Generally, people keep a line width of about 80 characters
    • However, with larger displays nowadays, it's not bad to extend this limit to 100 or even 120 characters
  • Similar to vertical openness, we now use white space to maintain horizontal openness

    • For instance, adding white space on either side of assignment operators or statements to make the left and right side elements distinct
    • Adding a white space after a comma for function parameters to accentuate separate arguments
  • Horizontal alignment is not as useful as it seems, keep unaligned declarations and assignments

    • Looking at the example, it's emphasising the wrong things, the variable name, data type and membership are less associated now
    public class ReporterConfig {
        private     String      breed;
        private     String      gender;
        private     int         age;
        private     String      name;
        private     boolean     isTheDogReallyFat;
    
        public Dog(breed, gender, age, name, isFat) {
            this.breed =        breed;
            this.gender =       gender;
            this.age =          age;
            this.name =         name;
            isTheDogReallyFat = isFat;
        }
    
        ...
    }
    
  • Code without indentation is practically unreadable

    • Indenting code highlights the hierarchy structure and allows us to visualise what scopes we're working in
    public class ReporterConfig { private String breed;private String gender;private int age;
    private String name;private boolean isTheDogReallyFat; public Dog(breed, gender, age, name, isFat) 
    {this.breed = breed;this.gender = gender;this.age = age;this.name = name;isTheDogReallyFat = isFat;}}
    
    • Often, it's tempting to omit indentation for single line if statements or even while loops
    • It's better to just add the indentation for styling consistency
    if (number == 1) { return true; }
    

Rules

  • Every programmer has their own unique way of formatting their code
  • In a team environment, everyone should agree upon a general styling guideline to follow
  • We ensure the system is maintainable and extendable, has a good set of documentation and is consistent and smooth across the board