Understand the Demeter principle in Java design pattern programming

  • 2020-05-05 11:15:05
  • OfStack

Definition: an object should have minimal knowledge of other objects.
The problem: the closer the relationship between classes, the greater the coupling, and when one class changes, the greater the impact on another class.
Solution: minimize coupling between classes.
Ever since we were introduced to programming, we have known the general principles of software programming: low coupling, high cohesion. In both procedural and object oriented programming, only by keeping the coupling between modules as low as possible can the code reuse rate be improved. The benefits of low coupling are obvious, but how do you program for it? That's what Demeter's law does.
Also known as the least known principle, the Demeter's rule was first proposed in 1987 by Ian Holland of Northeastern University in the United States. In layman's terms, the less a class knows about the class it depends on, the better. That is to say, for the dependent classes, no matter how complex the logic is, try to encapsulate the logic inside the class, and do not disclose any information except the public method. There is a simpler definition of Demeter's rule: only communicate with direct friends. First, let's explain what a direct friend is: every object has a coupling relationship with another object, and as long as there is a coupling relationship between two objects, we say the two objects are friends. There are many ways of coupling, dependency, association, composition, aggregation, and so on. Where, we call the class that appears in the member variable, method parameter, and method return value as a direct friend, while the class that appears in the local variable is not a direct friend. That is, unfamiliar classes are best not to appear inside a class as local variables.

Here is an example of a violation of the Demeter principle:


public class Teacher { 
 public void teach(Classes classes){ 
  classes.getStudents.getScore.show(); 
 } 
} 


What's the problem? Too much coupling.
1. The Score class may be canceled in the Student class.
2. The show method of the Score class may also be deleted.
The Student and Score classes are new to you, and you may not even know when they change.
We can change it to


public class Teacher { 
 public void teach(Classes classes){ 
  classes.showScore(); 
 } 
} 
 
public class Classes { 
 public void showScore(Student student){ 
  student.showScore(); 
 } 
} 
 
public class Student { 
 Score score; 
 public void showScore(){ 
  score = new Score(80); 
  score.show(); 
 } 
} 


Conclusion:
1. The advantage of Demeter's rule is that it reduces the coupling between classes.
2. The disadvantage is that there will be more small methods, making the system messy, and the communication efficiency will be reduced.
3. Application in design mode: facade mode (Facade Pattern) and mediation mode (Mediator Pattern).


Related articles: