[閱讀筆記] Clean Code — Chapter 10 Classes

Question Kid
2 min readJan 29, 2021

Class Organization

  • Class: a list of variables (public static constants → private static variables → private instance variables)
  • There is seldom a good reason to have a public variable
  • Functions: public function → private utilities (stepdown rule)

Encapsulation

  • maintain privacy but in some case protected (accessible for testing)

Classes Should Be Small!

  • The primary rule of designing classes: smaller (with respect to responsibility)
  • The name of a class should describe what responsibilities it fulfills → concise name (bad: Processor or Manager or Super)
  • Brief description of the class in about 25 words without IF, AND, OR, BUT

The Single Responsibility Principle

  • Classes should have one responsibility — one reason to change
  • Many small classes > few large classes

Cohesion

  • High cohesion: Each of the methods of a class should manipulate one or more of those variables
public class Stack {  
private int topOfStack = 0;
List elements = new LinkedList();
public int size() {
// use topOfStack;
}
public void push(int element) {
// use topOfStack, elements
}
public int pop() throws PoppedWhenEmpty {
// use topOfStack, elements
}

Maintaining Cohesion Results in Many Small Classes

  • When classes lose cohesion → split them
  • Ex. PrintPrimes → PrimePrinter, RowColumnPagePrinter, PrimeGenerator

Organizing for Change

  • Open-Closed Principle: Classes should be open for extension but closed for modification
  • When need to “open up” to modifications → check responsibility

Isolating form Change

  • Concrete classes: contain implementation details
    Abstract classes: represent concepts only
  • Bad: If the lower layer changed → the higher layer should be changed
  • Dependency Inversion Principle: classes should depend upon abstractions, not on concrete details
Previous Design
DIP Design

--

--

Question Kid

An interactive engineer based in Tokyo. CG/Unity/Coding/Book Review