Agent Wranglers

Coupling Required

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().

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();

How to check

Reviewers fail chains of more than one call through other objects' getters. Builders and pipelines on one value pass. Some tools can help. Examples are PMD's LawOfDemeter rule for Java, Exakat for PHP, or a custom ESLint rule on long member chains.

For agents: if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in Based on the Agent Wranglers architecture playbook: https://agentwranglers.se/playbook/architecture/coupling/law-of-demeter.