Ugly code: The Law of Demeter

By , last updated September 13, 2017

There is a heuristic called the Law of Demeter (LoD) or Principle of Least Knowledge that says 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

So the following Java code 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.


Be the first to comment.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>