Demystifying the Law of Demeter principle

The Law of Demeter principle reduces dependencies and helps build components that are loose coupled for code reuse, easier maintenance, and testability

lawofdemeter

The Law of Demeter (or the Principle of Least Knowledge) is a design guideline for developing software applications. First discussed at the Northeastern University in 1987, this principle states that an object should never know the internal details of other objects. It was designed to promote loose coupling in software designs.

Note that coupling may be defined as the degree of interdependence that exists between software modules and how closely such modules are connected to each other. The more the coupling between the components in an application, the harder it becomes to modify and maintain it over time. It's always a good practice to design systems that are easier to test and maintain by ensuring that the components in an application are loosely coupled. You can learn more on cohesion and coupling from my article here.

Understanding the Law of Demeter principle

The Law of Demeter principle states that a module should not have the knowledge on the inner details of the objects it manipulates. In other words, a software component or an object should not have the knowledge of the internal working of other objects or components. Let's understand the Law of Demeter with an example.

Consider three classes namely -- A, B, and C -- and objects of these classes -- objA, objB, and objC respectively. Now suppose objA is dependent on objB, which in turn composes objC. In this scenerio, objA can invoke methods and properties of objB but not objC.

The Law of Demeter principle takes advantage of encapsulation to achieve this isolation and reduce coupling amongst the components of your application. This helps in improving the code quality and promotes flexibility and easier code maintenance. The benefit of adhering to the Law of Demeter is that you can build software that is easily maintainable and adaptable to future changes.

Consider a class C having a method M. Now suppose you have created an instance of the class C named O. The Law of Demeter specifies that the method M can invoke the following types of .or a property of a class should invoke the following type of members only:

  • The same object, i.e., the object “O” itself
  • Objects that have been passed as an argument to the method “M”
  • Local objects, i.e., objects that have been created inside the method “M”
  • Global objects that are accessible by the object “O”
  • Direct component objects of the object “O”

Here’s a code listing that illustrates a class and its members that adhere to the Law of Demeter principle. I've mentioned comments wherever applicable for clarity.

public class LawOfDemeterExample

    {

        //This is an instance in the class scope

        //and hence this instance can be accessed by any members of this class

        AnotherClass instance = new AnotherClass();

       public void SampleMethodFollowingLoD(Test obj)

        {         

            DoNothing(); //This is a valid call as you are calling a method of the same class

             object data = obj.GetData(); //This is also valid since you are calling a method

            //on an instance that has been passed as a parameter           

             int result = instance.GetResult();  //This is also a valid call as you are calling

            //a method on an instance locally created

        }

        private void DoNothing()

        {

            // Write some code here

        }

    }

Here are the two other classes that you would need to compile the above code.

public class AnotherClass

    {

        public int GetResult()

        {

            return -1;

        }

    }

    public class Test

    {

        public object GetData()

        {

            return null;

        }

    }

Now, refer to the LawOfDemeterExample class shown above. The code is self-explanatory. You might now wonder if the Law of Demeter applies only to methods. The answer is "No". The Law of Demeter principle applies to properties as well.

Law of Demeter Principle violations

In the first code example explained earlier, we started our discussion on this topic by adhering to the Law of Demeter principle. Let’s understand what happens when we don’t follow this principle. Consider this code example.

var data = new A().GetObjectB().GetObjectC().GetData();

In this example, the client will have to depend on classes A, B and C. In other words, it is coupled to instances of the classes A, B and C. If in the future these classes change, you would run into trouble as you are exposing yourself to changes that might occur in any of these classes in future.

This article is published as part of the IDG Contributor Network. Want to Join?

From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.