Ugly code: The Law of Demeter

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 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();
VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Leave a Reply

Leave a Reply
  • (required)
  • (required) (will not be published)