Law of Demeter (LoD)

Back to Index

Introduction

The Law of Demeter (LoD), also known as the Principle of Least Knowledge, is a design guideline aimed at reducing the coupling between components in a system. It states that a module should only communicate with its immediate collaborators and not with distant objects.

Benefits

Rules

The Law of Demeter suggests that an object should only call methods of:

Example

Consider the following code where Customer accesses methods of Order and Product:

class Product {
    double getPrice() {
        return 100.0;
    }
}

class Order {
    private Product product;

    Order(Product product) {
        this.product = product;
    }

    Product getProduct() {
        return product;
    }
}

class Customer {
    private Order order;

    Customer(Order order) {
        this.order = order;
    }

    double getProductPrice() {
        return order.getProduct().getPrice();
    }
}
            

This violates LoD because Customer interacts with Order and Product. To adhere to LoD, delegate the responsibility to Order:

class Product {
    double getPrice() {
        return 100.0;
    }
}

class Order {
    private Product product;

    Order(Product product) {
        this.product = product;
    }

    double getProductPrice() {
        return product.getPrice();
    }
}

class Customer {
    private Order order;

    Customer(Order order) {
        this.order = order;
    }

    double getProductPrice() {
        return order.getProductPrice();
    }
}
            

Takeaway

By following the Law of Demeter, you reduce dependencies and make your system more robust and adaptable to changes.

Back to Index