Ugly code: The Law of Demeter

By , last updated January 28, 2016

I’ve recently come to 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

And that”s all!

So the following Java code appears to violate the Law:

String output = obj.getContext().getOptions().getDir().getPath();

It’s easy to forget something around such a structure. This one can solve the issue:

String output = obj.getPathFromContext();

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>