joydip_kanjilal
Contributor

Demystifying the Law of Demeter principle

opinion
Oct 27, 20164 mins
Software Development

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

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.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author