Introduction
The Law of Demeter is also know as the Principle of Least Knowledge. It is a software design guideline specially related to loose coupling. It was proposed by Ian Holland. This law mentions the below basic rules,
- Don't talk to Strangers:
- Don't send messages to objects returned from other message sends.
- Only talk to your immediate friends.
Let "M" is a method and "O" is an object so, M of object "O" should invoke only the methods of following kinds of objects,
- Itself
- Its Parameters
- It direct component object
- Any object it creates or instantiates
The Law of Demeter Violation
Below code example is a violation of the Law of Demeter,
- public class Test1
- {
- public Test4 test4 { get; set; }
- public Test2 test2 { get; set; }
-
- public Test1()
- {
- test4 = new Test4();
- test2 = new Test2();
- }
-
- public void Method1()
- {
- test2.test3.Test3Method();
- test4.test5.Test5Method();
- }
- }
- public class Test2
- {
- public Test3 test3 { get; set; }
-
- public Test2()
- {
- test3 = new Test3();
- }
- }
-
- public class Test3
- {
- public void Test3Method() { }
- }
-
- public class Test4
- {
- public Test5 test5 { get; set; }
- public Test4()
- {
- test5 = new Test5();
- }
- }
-
- public class Test5
- {
- public void Test5Method() { }
- }
In the above code, Method1() of class Test1 is calling the methods of classes Test3 and Test5 by using classes Test2 and Test5 respectively. Class Test1 is not aware of classes Test3 and Test5. Both classes are stranger for the class Test1. So, this code is violating the rule of Demeter Principle.
Basically, the Law of Demeter is focused on Coupling. If class Test1 needs to know about class Test3 or any other class then it is a violation. It clearly defines the need of two things in the code - first, Balance the need of Decoupling and second, keep the responsibility clearly separated.
The main purpose of this law is to restrict outside objects being able to access the internals of another object. Accessing internals encounters problems,
- It might give information about the internal structure of the object.
- Outside object can modify the internal structure of object
How can we obey the Law of Demeter if Multiple Levels of Class Dependencies are there?
The below rules should be followed to obey the Law of Demeter,
- Apply Aggregation
- Apply Composition
- Use good encapsulation at each level.
Conclusion
The Law of Demeter states that "you should only speak to objects that you know about directly". Do not do method chaining communication with other objects. By doing this it increases coupling.