Agent Wranglers

ARC-35Recommended

Talk only to your direct neighbours

A function calls methods on its own object, its arguments and the objects it creates. It never reaches through one object to steer another, as in a.getB().getC().doSomething().

How to do it

When you need something deep inside an object, ask that object to do the work. Add a method on the nearest object that hides the path. Data objects with public fields are fine to read, because they have no behaviour to hide. Chains on one object are fine too. Examples are fluent builders such as z.string().trim() and collection pipelines such as items.map().filter(). Give the object a command, as Tell objects what to do says.

Examples

JavaScript example

// Bad: the checkout knows how a customer stores their wallet
const card = order.getCustomer().getWallet().getDefaultCard();
card.charge(order.total());

// Good: the order asks its customer, who asks its wallet
order.collectPayment();

Python example

# Bad
card = order.customer.wallet.default_card
card.charge(order.total)

# Good
order.collect_payment()

How to check

A lint rule or a grep fails a method call on an object returned by another object's getter, such as order.getCustomer().getAddress(). Reviewers fail any that slip past. Builders and pipelines on one value pass. Example tools are PMD's LawOfDemeter rule for Java, Exakat for PHP, or a custom ESLint rule on long member chains.

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/architecture/coupling/law-of-demeter">Agent Wranglers clean code and architecture playbook</a>. In code you write, add a comment next to it with the same link.