DEV Community

Cover image for Law of Demeter (Principle of Least Knowledge)
Daniel Azevedo
Daniel Azevedo

Posted on

Law of Demeter (Principle of Least Knowledge)

Hi devs,

If you've been coding for a while, you've probably encountered code that's difficult to maintain or extend. Often, this happens because parts of the system know too much about each other. That’s where the Law of Demeter, or the Principle of Least Knowledge, comes into play.

This principle is all about reducing dependencies in your code and keeping objects focused on their own responsibilities. In simple terms, it says that an object should only talk to its close “friends,” not to strangers or friends of friends. It sounds like social advice, but it applies perfectly to clean and maintainable code!


What Is the Law of Demeter?

The Law of Demeter (LoD) is a design guideline for developing software, particularly in object-oriented programming. The main idea is that a method of an object should only call methods on objects that are directly related to it—meaning no reaching deep into object chains to grab what you need.

This principle helps to reduce coupling and makes your code easier to change and maintain. By following this rule, you’re preventing objects from depending too much on the inner workings of other objects, which can lead to brittle systems that break with even small changes.


The Core Rule

The basic rule of the Law of Demeter is:

A method M of an object O should only call the following methods:

  • Methods of O itself.
  • Methods of objects passed as arguments to M.
  • Methods of objects that are created by M.
  • Methods of objects that are held in instance variables of O.

If you find yourself chaining calls like objectA.getB().getC().doSomething(), you're probably violating this principle. The idea is to stop that chain at getB() or earlier.


Why Should We Care?

By adhering to the Law of Demeter, you can significantly reduce coupling between classes, which leads to more modular, adaptable code. When objects know less about each other’s internal workings, the system becomes more robust and less prone to break when you refactor.

Let’s look at an example in C# to make this clearer.


Example: Violating the Law of Demeter

Here’s a simple scenario where the Law of Demeter is violated. Let’s say we have a Payroll system where an employee’s salary depends on their department’s budget.

public class Employee
{
    public Department Department { get; set; }
}

public class Department
{
    public Budget Budget { get; set; }
}

public class Budget
{
    public decimal SalaryCap { get; set; }
}

public class Payroll
{
    public decimal CalculateSalary(Employee employee)
    {
        // Violates Law of Demeter
        return employee.Department.Budget.SalaryCap * 0.5m;
    }
}
Enter fullscreen mode Exit fullscreen mode

In the CalculateSalary method, we are reaching deep into the Employee object’s relationships to access SalaryCap from the Budget. This chain of method calls breaks the Law of Demeter, as Payroll knows too much about the structure of Employee, Department, and Budget.


How to Fix This?

We can refactor this code by applying the Law of Demeter, making each class responsible for its own data and keeping interactions more localized.

public class Employee
{
    public Department Department { get; set; }

    public decimal GetSalaryCap()
    {
        return Department.GetSalaryCap();
    }
}

public class Department
{
    public Budget Budget { get; set; }

    public decimal GetSalaryCap()
    {
        return Budget.SalaryCap;
    }
}

public class Payroll
{
    public decimal CalculateSalary(Employee employee)
    {
        // Law of Demeter applied
        return employee.GetSalaryCap() * 0.5m;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, the Payroll class only interacts with the Employee object directly, and the Employee is responsible for knowing about the Department and Budget. This reduces the coupling and makes the system more resilient to change.


Key Benefits of the Law of Demeter

  1. Loose Coupling: When classes know less about each other, they’re less tightly bound, making changes easier and safer.
  2. Easier Maintenance: With fewer dependencies, refactoring becomes much less risky.
  3. Improved Readability: It’s easier to understand the flow of the code when objects have clear boundaries and minimal interaction with distant objects.
  4. Better Testability: Classes that follow the Law of Demeter are often easier to mock and test in isolation since they’re not dependent on long chains of objects.

Final Thoughts

The Law of Demeter might seem like a strict rule at first, but when you apply it consistently, it really helps in writing clean, maintainable code. It forces you to think about object interactions and encourages designing smaller, more focused classes.

However, as with any principle, don't apply it blindly. In some cases, a small violation might be justified if it simplifies your code without introducing too much risk. Always balance clean design with practical implementation.
Keep coding!!

Top comments (0)