Series Clean Code - Classes

Continue the Clean Code series, today I'll talk about Classes topic. This is also one of the best important thing need to focus in writing code because when we work, we have more than hundred, even up to thousands of classes in project. If you write arbitrary functions, no rules at all, maybe the program is still running. But when you need to upgrade or maintaining, you may have trouble in reading that messy code. So, we will have some rules to write classes.
Class Organization
  • Class should start with a list of variables:
    - public static constants / variables
    - private static variables
    - private instance variables
    - public instance variables (rarely have a good reason to use) 
  • public functions, placed after the list of variables. 
  • private utilities function, which is placed after the public function calls it >> this follows the step down rule and helps the program be read as an article.
Encapsulation
  • Encapsulation is an information hiding principle. 
  • Only the information that needs to be shared outside the access will be passed to the accessors (getter / setter || properties).

  • Encapsulation helps to adapt well to change, particularly when changing the data type of an attribute in an object. 
  • For example, the initial time attribute of the Record class is a String for the purpose of storing time in the format hh:mm:ss. Then you realize that time should be of type int for seconds, it is better to compare the two times, but when the time display is still in format hh:mm:ss
 

Classes Should Be Small
  • Just as Functions, the smaller is the first rule when it comes to designing Classes >> how small is it enough?
 
  • With Functions, we measure by counting the number of lines. With Classes, we measure in other ways, we count responsibilities. 
  • We can write a short description for the class with about 25 words >> counting responsibility. 
  • "The SuperDashboard provides access to the component that last held the focus, and it also allows us to track the build and version numbers." 
Cohesion
  • Class should limit the number of variables, and methods in the class manipulate at least one of these variables to increase cohesion. 
  • The cohesion here is that the methods and variables of the class are both dependent and interconnected as a logical whole.
 

Organizing for Change
  • For every system, change is continuous. 
  • Each change leads to the risk that the rest of the system will no longer function as intended. 
  • In a clean system, we organize classes to reduce the risk of change.
Isolating from Change
  • Isolation (isolation) >> Loose Coupling || Low Coupling || Decoupling. 
  • A client class depends on a specific detail of the risk when details change, and we can pass on interfaces and abstract classes to help isolate changes to those details.
See you in next chapter about OOT (Object Oriented Tricks)...

0 nhận xét:

Đăng nhận xét

Được tạo bởi Blogger.