In this article we will explain the heuristic called the Law of Demeter (LoD) and give an example of how it works in Java.
The Law of Demeter or Principle of Least Knowledge says that a module should not know about the innards of the objects it manipulates. More precisely, the method of a particular class should call:
Here’s an example Java code that appears to violate the Law:
String output = obj.getContext().getOptions().getDir().getPath();
It’s easy to forget something around this train structure.
In order to solve the issue consider encapsulating the logic:
String output = obj.getPathFromContext();
More on programming basics.
Senior Software Engineer developing all kinds of stuff.