This post is part of clean code’s series, you can check the previous parts from here
Today, I will cover Chapter 10
- Class Organization
Following the standard Java convention, a class should begin with a list of variables. Public static constants, if any, should come first. Then private static variables, followed by private instance variables. Public functions should follow the list of variables.
We like to keep our variables and utility functions private.
- Classes Should Be Small!
The first rule of classes is that they should be small. The second rule of classes is that they should be smaller than that. With functions we measured size by counting physical lines. With classes we count responsibilities. The name of a class should describe what responsibilities it fulfills.
- The Single Responsibility Principle [SRP]
It states that a class or module should have one, and only one, reason to change.
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.
Classes should have a small number of instance variables. Each of the methods of a class should manipulate one or more of those variables.
A class in which each variable is used by each method is maximally cohesive.
When cohesion is high, it means that the methods and variables of the class are co-dependent and hang together as a logical whole.
- Maintaining Cohesion Results in Many Small Classes
- Organizing for Change
In a clean system we organize our classes so as to reduce the risk of change.
- Open-Closed Principle [OCP]
Classes should be open for extension but closed for modification.
- Isolating from Change
Needs will change, therefore code will change.
A client class depending upon concrete details is at risk when those details change.
- Dependency Inversion Principle [DIP]
Classes should depend upon abstractions, not on concrete details.
One day, someone gonna read your code and appreciate it saying “It’s a piece of Art” 😀