1. Overview

The Law of Demeter (LoD), or principle of least knowledge, provides object-oriented design principles for modular software development. It helps to build components that are less dependent on each other and loosely coupled.

In this tutorial, we’ll delve into the Law of Demeter and its application in Java.

2. Understanding the Law of Demeter

The Law of Demeter is one of several design guidelines in object-oriented programming. It recommends that objects should avoid accessing the internal data and methods of other objects. Instead, an object should only interact with its immediate dependencies.

The concept was first introduced in a paper by Karl J. Lieberherr, et al. It states that:

For all classes C, and for all methods M attached to C, all objects to which M sends a message must be instances of classes associated with the following classes:

  • The argument classes of M (including C)
  • The instance variable of classes of C

(Objects created by M, or by functions or methods which M calls, and objects in global variables are considered as arguments of M.)

Simply put, the Law says that a method X of class C should only invoke the methods of:

  • Class C itself
  • An object created by X
  •  An object passed as an argument to X
  •  An object held in an instance variable of C
  • A static field

This sums up the law in five points.

3. Examples of the Law of Demeter in Java

In the previous section, we distilled the Law of Demeter into five key rules. Let’s illustrate these points with some sample code.

3.1. The First Rule

The first rule says that a method X of class C should only invoke the methods of C:

class Greetings {
    
    String generalGreeting() {
        return "Welcome" + world();
    }
    String world() {
        return "Hello World";
    }
}

Here, the generalGreeting() method invokes the world() methods in the same class. This adheres to the law as they belong to the same class.

3.2. The Second Rule

Method X of class C should only invoke the methods of an object created by X:

String getHelloBrazil() {
    HelloCountries helloCountries = new HelloCountries();
    return helloCountries.helloBrazil();
}

In the code above, we create an object of HelloCountries and invoke helloBrazil() on it. This follows the law as the getHelloBrazil() method itself created the object.

3.3. The Third Rule

Furthermore, the third rule state that method X should only invoke an object passed as an argument to X:

String getHelloIndia(HelloCountries helloCountries) {
    return helloCountries.helloIndia();
}

Here, we pass an HelloCountries object as an argument to getHelloIndia(). Passing the object as an argument gave the method close proximity to the object, and it can invoke its method without violating the rule of Demeter.

3.4. The Fourth Rule

Method X of class C should only invoke the method of an object held in an instance variable of C:

// ... 
HelloCountries helloCountries = new HelloCountries();
  
String getHelloJapan() {
    return helloCountries.helloJapan();
}
// ...

In the code above, we create an instance variable, “helloCountries“, in the Greetings class. Then, we invoke the helloJapan() method on the instance variable inside the getHelloJapan() method. This conforms to the fourth rule.

3.5. The Fifth Rule

Finally, method X of class C can invoke the method of a static field created in C:

// ...
static HelloCountries helloCountriesStatic = new HelloCountries();
    
String getHellStaticWorld() {
    return helloCountriesStatic.helloStaticWorld();
}
// ...

Here, the method invokes helloStaticWorld() method on a static object created in the class.

4. Violating the Law of Demeter

Let’s examine some sample code that violates the Law of Demeter and look at a possible fix.

4.1. Setup

We’ll begin by defining an Employee class:

class Employee {
  
    private Department department = new Deparment();
  
    public Department getDepartment() {
        return department;
    }
}

The Employee class contains an object reference member variable and provides accessor methods for it.

Moving on, the Department class is defined with the following member variables and methods:

class Department {
    private Manager manager = new Manager();
  
    public Manager getManager() {
        return manager; 
    }
}

Furthermore, the Manager class contains the method to approve expenses:

class Manager {
    public void approveExpense(Expenses expenses) {
        System.out.println("Total amounts approved" + expenses.total())
    }
}

Finally, let’s look at the Expenses class:

class Expenses {
    
    private double total;
    private double tax;
    
    public Expenses(double total, double tax) {
        this.total = total;
        this.tax = tax;
    }
    
    public double total() {
        return total + tax;
    }
}

4.2. Usage

The classes exhibit tight coupling through their relationships. We’ll demonstrate a Law of Demeter violation by having the Manager approve Expenses:

Expenses expenses = new Expenses(100, 10); 
Employee employee = new Employee();
employee.getDepartment().getManager().approveExpense(expenses);

In the code above, we have chained calls that violate the Law of Demeter. The classes are tightly coupled and cannot operate independently.

Let’s fix this violation by having the Manager class as an instance variable in Employee. It will be passed in via the Employee constructor. Then, we’ll create submitExpense() method in the Employee class and invoke approveExpense() on Manager inside it:

// ...
private Manager manager;
Employee(Manager manager) {
    this.manager = manager;
}
    
void submitExpense(Expenses expenses) {
    manager.approveExpense(expenses);
}
// ...

Here’s the new usage:

Manager mgr = new Manager();
Employee emp = new Employee(mgr);
emp.submitExpense(expenses);

This revised approach adheres to the Law of Demeter by reducing the coupling between classes and promoting a more modular design.

5. Exception to the Law of Demeter

Chained calls usually signal a violation of the Law of Demeter, but there are exceptions. For example, the builder pattern doesn’t violate the Law of Demeter if the builder is instantiated locally. One of the rules states that “Method X of class C should only invoke the methods of an object created by X“.

Additionally, there are chained calls in Fluent APIs. Fluent APIs don’t violate the Law of Demeter if the chained calls are on locally created objects. But when the chained calls are on a non-locally instantiated object or returns a different object, then it violates the Law of Demeter.

Also, there are cases where we could violate the Law of Demeter when dealing with data structures. The typical data structure usage, like instantiating, mutating, and accessing them locally, doesn’t violate the Law of Demeter. In a case where we’re calling a method on an object obtained from a data structure, then the Law of Demeter may be violated.

6. Conclusion

In this article, we learned the application of the Law of Demeter and how to adhere to it in object-oriented code. Additionally, we delved into each law with code examples. The Law of Demeter promotes loose coupling by limiting object interactions to immediate dependencies.

As always, the complete source code for the examples is available over on GitHub.