Also known as the Principle of Least Knowledge, the Law of Demeter states that objects should avoid accessing data and methods that belong in other classes and instead, only interact with its immediate dependencies (Baeldung).
When used with Object-Programming languages, the goal of the Law of Demeter is to make the components of a program less dependent on each other, loosely coupled, and therefore easier to manage and scale.
There are five rules to the Law of Demeter:
- The first states that methods should only call methods that belong to their same class. It is not recommended for a method in class X, for example, to call on another method in class Y.
- The second rule expands on the first to say that methods of a class should only call methods that belong to the objects created by that class. For example, a method X of a class Z should only call methods of an object created by method X.
- The third rule states that a method should only ever interact with an object when passed to it as an argument. There should be no direct access to the object within the method itself.
- The fourth rule allows the method of a class to invoke the method of a class given that it is an instance variable of the same class. For example, method X of class C is allowed to call the method of an object held as an instance variable of C.
- The fifth rule is similar to the fourth rule except it states that the method of a class is able to call the method of a static field in that same class, similar to a method of an object of the same class.
When these rules of the Law of Demeter are applied, they help prevent code from becoming tightly coupled, meaning that they cannot operate independently. However, there are some exceptions to certain cases such as for chain calling, fluent APIs, or working with data structures. An experienced programmer will know when and how to effectively apply the law of Demeter.
While refactoring the code for one of my research projects, I had practiced to apply the GRASP principles to the new design. For another project that I am refactoring, now that I am more comfortable with the GRASP principle, I will focus more on applying the law of Demeter to make sure my code is not tightly coupled. This means code that is less fragile, scalable, and easier to manage.
Source: https://www.baeldung.com/java-demeter-law
From the blog Stories by Namson Nguyen on Medium by Namson Nguyen and used with permission of the author. All other rights reserved by the author.