Ugly code: The Law of Demeter

By , last updated August 19, 2019

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:

  • other methods of the same class
  • objects created by the method itself
  • objects passed as arguments to the method
  • objects held in an instance variable of the same class

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.