Skip to content
Law of Demeter — Explained with Examples

Law of Demeter — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

The Law of Demeter (principle of least knowledge) states that a module should only communicate with its immediate neighbors, not with strangers.

Law of Demeter (LoD), also called the Principle of Least Knowledge, was named after the Demeter project at Northeastern University. It restricts method calls to: the object itself, its own fields, method parameters, objects it creates, and objects in collections it holds.

Why It Matters

Chained calls like customer.getOrder().getItem().getPrice() create tight coupling. The calling code must know the structure of three different classes. If getOrder() changes to return a different type, all chains break. LoD reduces coupling by enforcing that objects only talk to their direct neighbors.

Real-World Analogy

A hotel guest doesn’t call the chef directly to order room service. They call the front desk (immediate neighbor), which contacts the kitchen (front desk’s neighbor), which tells the chef (kitchen’s neighbor). The guest only knows about the front desk, not the entire hotel hierarchy.

Example: Violating vs Following LoD

# Violating Law of Demeter — train wreck
class Customer:
    def __init__(self):
        self._wallet = None

    def get_wallet(self):
        return self._wallet

class Wallet:
    def __init__(self, cash):
        self._cash = cash

    def get_cash(self):
        return self._cash

# Client code — knows Customer, Wallet, and their internals
def pay_customer(customer, amount):
    cash = customer.get_wallet().get_cash()  # Train wreck!
    if cash >= amount:
        # process payment
        pass
# Following Law of Demeter — tell, don't ask
class Customer:
    def __init__(self):
        self._wallet = Wallet(0)

    def can_pay(self, amount):
        return self._wallet.has_funds(amount)

class Wallet:
    def __init__(self, cash):
        self._cash = cash

    def has_funds(self, amount):
        return self._cash >= amount

# Client code — only talks to Customer
def pay_customer(customer, amount):
    if customer.can_pay(amount):  # Single call, no chain
        print(f"Customer can pay ${amount}")
    else:
        print(f"Insufficient funds")

Related Terms

Encapsulation, Composition over Inheritance, Single Responsibility Principle

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro