今日推荐英文原文：《Demeter’s Law: Don’t talk to strangers!》
今日推荐英文原文：《Demeter’s Law: Don’t talk to strangers!》作者：Carlos Caballero
Demeter’s Law: Don’t talk to strangers!
Software Engineering Principles
The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs.— WikipediaThis law was proposed by Ian Holland in 1987. Holland and colleagues were programming a system called Demeter using oriented object programming. During the development of the system, they realized that the code that fulfilled a series of rules was less coupled.
Demeter’s law is known as “don’t talk to strangers” because:
- Each unit should have only limited knowledge about other units — only units “closely” related to the current unit.
- Each unit should only talk to its friends — don’t talk to strangers.
- Only talk to your immediate friends.
- O itself.
- m’s parameters.
- Any objects created/instantiated within m.
- O’s direct component objects.
- A global variable, accessible by O, in the scope of m.
In this case, an object a from the A class can request a method of an object instanced of B class but the object A should not reach object B directly, because that would mean the object A has greater knowledge of object B’s internal structure (tight coupling).
The following image illustrates who are friends between class relations:
Real example — Person → House → AddressNow, I am going to show a real example implemented with TypeScript. In the following UML diagram you can see as a Person is related to House and House is related to Address.
The original code is from https://github.com/tavaresasilva/LoDRaV, coded using JAVA.
The following code can be run in the client/context, whereas the first code broke Demeter’s Law due to Person requiring knowledge about the inner implementation of the class House. On the other hand, the second implementation respects Demeter’s Law and the code is less coupled.
The following steps show you must implement the code to respect Demeter’s Law and obtain a less coupled code. So, the first step is to create the interface which will be implemented in our concrete classes:
The next step will be the implementation of the concrete classes as you can see below:
The most important thing in the code is that no method violated Demeter’s Law (there are not more than two consecutive invocations of contained objects).
Here’s another example in which the Demeter’s Law is broken:
In this case, the solution is to implement isZipCode method in class person, as you can see in the following code:
AdvantagesThe main advantages of satisfying Demeter’s Law are:
- Dependencies between classes and coupling are reduced.
- Classes can be reused with ease.
- The code is easier to test.
- The code is more maintainable and flexible to changes.