Code quality and technical debt

Law of Demeter

Also known as Law of Demeter, Law of Demeter in software engineering

By WeavePublished 1 min read

Definition

A guideline that limits how many unrelated object relationships a method navigates directly.

What it means

The Law of Demeter encourages a method to talk to close collaborators rather than reaching through chains of objects. Expressions such as order.customer.account.address can expose knowledge of internal structure and make changes ripple across callers. The guideline favors messages that match responsibility boundaries.

Example

A notification service asks an order for a delivery address instead of navigating through customer, account, and profile objects. The order owns the path to its address and can change its internal representation.

Limitations

Strictly banning every chained call can produce needless forwarding methods and hide simple data access. Fluent APIs and immutable transformations may use chains intentionally. Consider coupling and change impact, not syntax alone.

How to use the signal

Judge the stability of the relationship behind a call chain instead of banning fluent or deliberately compositional APIs.

Weave can help identify whether navigation-heavy changes produce review iteration or rework. Static rules can find patterns, but engineers must decide whether the relationships are genuinely unstable.

How this relates to Weave

Weave can help identify whether navigation-heavy changes produce review iteration or rework. Static rules can find patterns, but engineers must decide whether the relationships are genuinely unstable.

Explore Engineering intelligence

Sources and further reading

  1. SonarSource code metrics and analysis documentation