Definition: One object should keep the least understanding of other objects.
The origin of the problem: the closer the relationship between classes, the greater the coupling degree, and when one class changes, the greater the impact on another class.
Solution: Minimize coupling between classes as much as possible.
Since we started to learn programming, we have known the general principles of software programming: low coupling, high cohesion. Whether it is process-oriented or object-oriented programming, the code reuse rate can be improved only by keeping the coupling between each module as low as possible. The advantages of low coupling are self-evident, but how can you program to achieve low coupling? That's exactly what the Dimit rule is going to accomplish.
The Dimitter Law, also known as the principle of least knowledge, was first proposed in 1987 by Ian Holland of Northeastern University in the United States. In layman's terms, the less you know about a class that depends on, the better. In other words, for the dependent class, no matter how complex the logic is, try to encapsulate the logic inside the class, and do not leak any information to the outside except the public method provided. The Dimit rule also has a simpler definition: only communicate with direct friends. First, let’s explain what a direct friend is: each object will have a coupled relationship with other objects. As long as there is a coupling relationship between the two objects, we will say that these two objects are a friend relationship. There are many ways to couple, such as dependency, association, combination, aggregation, etc. Among them, we call the class in the member variable, method parameters, and method return value that appears as direct friends, while the class in the local variable is not direct friends. In other words, it is best not to appear inside the class as a local variable.
Here is an example of a violation of the Dimit principle:
public class Teacher { public void teacher(Classes classes){ classes.getStudents.getScore.show(); } }
What are the problems? Too high coupling.
1. The Score class may be cancelled in the Student class.
2. The show method of the Score class may also be deleted.
Student classes and Score classes are all unfamiliar to you, and you may not know when they change.
We can modify it to:
public class Teacher { public void teacher(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(); } }
Summarize:
1. The advantage of Dimit's law is to reduce coupling between classes.
2. The disadvantage is that it will produce more small methods, making the system more messy and the communication efficiency will be reduced.
3. Applications in design mode: facade mode (Facade mode) and mediator mode (Mediator mode).