9. Classes - tuansondinh/clean_code GitHub Wiki

9.1 Class Organization

  1. begin with variables with following order:
  • public static constants, private static variables, private variables
  1. Public functions, then private functions (called by the public functions) -> stepdown rule
  • use protected, so it's accessible by tests

Try to keep variables and utility functions private.

9.2 Classes should be small!

  • size of a class can be measured by it's responsibilities
  • "The name of a class should describe what responsibilities it fulfills." S.138
  • "If we cannot derive a concise name for a class, then it’s likely too large." S.138

9.3 The Single Responsibility Principle

"The Single Responsibility Principle (SRP) states that a class or module should have one, and only one, reason to change." S.138

"Trying to identify responsibilities (reasons to change) often helps us recognize and create better abstractions in our code." S.139

BAD: (class also deals with version information)

public class SuperDashboard extends JFrame implements MetaDataUser {
  public Component getLastFocusedComponent()
  public void setLastFocused(Component lastFocused)
  public int getMajorVersionNumber()
  public int getMinorVersionNumber()
  public int getBuildNumber()
}

GOOD: (create a new class for it-> also high potential for reuse)

public class Version {
  public int getMajorVersionNumber()
  public int getMinorVersionNumber() 
  public int getBuildNumber()
}

"Getting software to work and making software clean are two very different activities.[...]The problem is that too many of us think that we are done once the program works." S.139

Conclusion "We want our systems to be composed of many small classes, not a few large ones. Each small class encapsulates a single responsibility, has a single reason to change, and collaborates with a few others to achieve the desired system behaviors." S.140

9.4 Cohesion (should be high)

  • classes should have only a few instance variables
  • each methods manipulates these variables
  • "the more variables a method manipulates, the more cohesive that method is to its class" S. 140
  • "A class in which each variable is used by each method is maximally cohesive." S.140

Maintaining Cohesion Results in Many Small Classes

  • break big functions into smaller ones, which share instance variables
  • Problem: more instance variables -> less cohesion
  • Solution: When classes lose cohesion -> split them!
  • functions that share the same instance variables -> own class

'So breaking a large function into many smaller functions often gives us the opportunity to split several smaller classes out as well. This gives our program a much better organization and a more transparent structure.' S.141

9.5 Organizing for Change

WIP