Ugly code: The Law of Demeter

Posted by Tatyana at 21 May 2010

Category: Dev, Java

Tags: , ,

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();

Related posts:

  1. Clean code
  2. Collision detection in practice
  3. Testing java with JUnit
  4. Intro C++
  5. PMD XPath: creating custom rules

Leave a Reply

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