For a good software design, it is very important to have “loosely coupled” classes. A coupling may be defined as the degree of inter dependency exists between software modules. The more coupling between the components in an application, it is harder to modify and maintain it over a period of time.
When we follow proper design principle in our day to day development and based on that do the refactoring of our code, it definitely leads much clean, readable and more maintainable code.
According to Law of Demeter, for any class C, a method M belonging to C may only invoke following:
- The object class C itself
- Members of class C
- An argument of the method M
- Object created within the method M
- Global objects
In general terms it is often described this way:
“Only talk to your immediate friends.”
“Don’t talk to strangers.”
The Law of Demeter principle makes our code less coupled. A caller method is not coupled with all of the inner dependencies. It is only coupled with one object. Using this principle we can also change a class without effect to others.
This Law also improves encapsulation and abstraction while can enhance the test ability of code.
Tips to identify
Law of Demeter is more of a guideline than a principle to help reduce coupling between components. There are below general outcome of the code when we avoid this law:
- Dots counting
- Too many wrapper classes
Let’s take a look at below bad code of dots counting in JAVA:
In short, the Law of Demeter aims to keep away from doing things like this and try to make it simpler like this:
We discussed lots of theory. So let’s see some code of example in Java to explain Law of Demeter. Here you can see, while we are getting the value of primaryEmailAddress and mobile, LOD is getting violated.
Now to fix this violation, we have shifted the validation of primaryEmailAddress and mobile within Employee object method, named as isValidPrimaryEmailAddress () and isValidMobile().
You can find a basic code of above explanation from GitHub.
In general rule we don’t want our methods to know about the entire object map of the application. Each individual methods should have a single responsibility and limited knowledge. The principle of least knowledge or LOD reduces dependencies and helps to build components that are loose coupled for code reuse, easier for maintenance, and testability.
It is hard to follow the design rules but once understand them properly, the benefits are obvious.
Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful. Stay tuned for upcoming articles. For any quires or suggestions, feel free to hit me on Twitter Google+
“Power is gained by sharing knowledge, not hoarding it”
Check out my blogger page for more interesting topics on Software development.