Skip to content
IT glossary
ProgrammingUpdated December 3, 2026

Law of Demeter

Закон Деметры

A design guideline that asks objects to work with their immediate collaborators rather than reach through them into other objects. This makes it easier to change how one object is built without changing its callers.

Also known as: принцип минимального знания

What it means

The Law of Demeter, also called the principle of least knowledge, is often summed up as “talk only to your immediate friends.” Suppose a shipping service needs a postal code to quote a price. It needs to know how to ask the order for that code, but it doesn't need to know which object inside the order stores it. Keeping that detail out of the shipping service reduces coupling: a change to the order's internal structure is less likely to ripple through its callers.

Who counts as an immediate collaborator?

In a common formulation, a method can call methods on its own object (this), its parameters, objects held directly in its object's fields, and objects it creates itself. An object reached through one of those collaborators isn't automatically a direct collaborator. Giving it a local variable makes the code easier to read, but it doesn't change what the caller needs to know about the object model.

Example: quoting a shipping rate

// The caller navigates from the order to its address.
return rates.forPostalCode(order.getShippingAddress().getPostalCode());

// The caller asks the order for the value it needs.
return rates.forPostalCode(order.shippingPostalCode());

If the order holds an address directly, shippingPostalCode() can read the postal code from that address. If shipping details later move to a separate fulfillment object, the order can change how it provides the code without changing the rate lookup. The order still owns the shipping details; the service still owns the decision about the rate.

When to use it

Look for it in domain code where several callers navigate the same set of nested objects. A task-specific method can put knowledge of those relationships in one place. Don't count dots, though. Builder methods may return the builder itself, and chained calls can be part of a deliberately fluent API. Similarly, reading nested fields in a data transfer object can be entirely appropriate when its structure is the public contract.

Avoid adding a forwarding method for every nested property. If the result is a class whose public API mirrors the objects inside it, reconsider which object should own the operation or whether callers need a separate read model.

In an interview

If you're asked to refactor a chain of getters, first say what relationships the caller depends on. Then name a concrete change that would break the original code but not your refactoring. That explains the design benefit more clearly than saying the new version has fewer dots.