Law of Demeter in Java – Principle of least Knowledge – Real life Example

Law of Demeter also known as principle of least knowledge is a coding principle, which says that a module should not know about the inner details of the objects it manipulates. If a code depends upon internal details of a particular object, there is good chance that it will break as soon as internal of that object changes. Since Encapsulation is all about hiding internal details of object and exposing only operations, it also assert Law of  Demeter. One mistake many Java programmer makes it exposing internal detail of object using getter methods and this is where principle of least knowledge alerts you. I first come to know about this principle, while reading one of the must read programming book, Robert C. Martin’s Clean code. Apart from many good thing the book teaches you, “principle of least knowledge” is one principle, which I still remember. Like many bad things, you will tempt to violate Law of Demeter, because of beautiful chaining of methods written in fluent style. On surface it looks pretty good, but as soon as you think about principle of least knowledge, you start seeing the real picture. In this article, we will see formal definition of Law of Demeter and explore code snippet which violates this principle.

Law of Demeter

According to Law of Demeter, a method M of object O should only call following types of methods :

  1. Methods of Object O itself
  2. Methods of Object passed as an argument
  3. Method of object, which is held in instance variable
  4. Any Object which is created locally in method M

More importantly method should not invoke methods on objects that are returned by any subsequent method calls specified above and as Clean Code says “talk to friends, not to strangers”. Apart from knowing object oriented programming basic concepts e.g. Abstraction, Polymorphism, Inheritance and SOLID design principle, it’s also worth knowing useful principle like this, which has found it’s way via experience. In following example, we will see how a method can violate above rules to violate Law of Delimiter.

public class LawOfDelimterDemo {

    /**
     * This method shows two violations of "Law of Delimiter" or "Principle of least knowledge".
     */
    public void process(Order o) {

        // as per rule 1, this method invocation is fine, because o is a argument of process() method
        Message msg = o.getMessage();

        // this method call is a violation, as we are using msg, which we got from Order.
        // We should ask order to normalize message, e.g. "o.normalizeMessage();"
        msg.normalize();

        // this is also a violation, instead using temporary variable it uses method chain.
        o.getMessage().normalize();

        // this is OK, a constructor call, not a method call.
        Instrument symbol = new Instrument();

        // as per rule 4, this method call is OK, because instance of Instrument is created locally.
        symbol.populate(); 

    }
}

You can see that when we get internal of Order class and  call a method on that object, we violate Law of delimiter, because now this method knows about Message class. On the other hand calling method on Order object is fine because its passed to the method as parameter.  This image nicely explains what you need to do to follow Law of Demeter.

Law of Demeter in Java with Example

Let’s see another example of code, which violates the Law of Demeter and how does it affect code quality.

public class XMLUtils {
   public Country getFirstBookCategoryFromXML(XMLMessage xml) { 
       return xml.getXML().getBooks().getBookArrary(0).getBookHeader().getBookCategory();
   }
}

This code is now dependent upon lot of classes e.g.
XMLMessage
XML
Book
BookHeader
BookCategory

Which means this function knows about XMLMessage, XML, Book, BookHeader and BookCategory. It knows that XML has list of
Book, which in-turn has BookHeader and which internally has BookCategory, that’s a lot of information. If any of the intermediate class or accessor method in this chained method call changes, then this code will break. This code is highly coupled and brittle. It’s much better to put the responsibility of finding internal data into the object, which owns it. If we look closely, we should only call getXML() method because its method from XMLMessage class, which is passed to method as argument. Instead of putting all this code in XMLUtils, should be putting on BookUtils or something similar, which can still follow Law of Demeter and can return the required information.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "Law of Demeter in Java – Principle of least Knowledge – Real life Example"

  1. incze says:

    you probably have a spell checker with that “law of delimiter”.

Leave a Reply


7 + five =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close