Patterncore
Message Chains
Also called train wreck.
A code smell: a client asks one object for another, then asks that one for a third, and so on, so the client depends on the whole path between the objects.
- Family
- code-smell
- Intent
- Find the clients that walk a chain of objects, and give the first object a method that answers the question, so that the path is known in one place.
- Refactorings
- Hide delegate, Extract function, Move function
Intent
Find the code that reaches through one object to get at another, and another after that. Give the first object in the chain a method that answers the question the client really has. Then the path between the objects is written in one place, and a change to the path is one edit.
Problem
A message chain is a line such as order.customer.address.country. The client asks the order for its customer, asks the customer for an address and asks the address for a country. Refactoring describes the smell this way: a client asks one object for another object, which the client then asks for yet another object, and so on.1 It adds the cost: the client is coupled to the structure of the navigation, and any change to the relationships in between forces the client to change.1
The design rule that the smell breaks is the Law of Demeter. Wikipedia sums it up as "Each unit should only talk to its friends; don't talk to strangers", and gives its object-oriented form: "an object should avoid invoking methods of an object returned by another method."2 It also gives the short version for languages with a dot: "use only one dot".2
The forces are these:
- Each step in the chain is a getter that is natural to write. The chain grows one dot at a time.
- The client needs one fact, but to get it the client must know three types and how they connect.
- The same chain appears in many clients. When the path changes, each copy must change, which is a form of Shotgun Surgery.
- Not every chain is a smell. A chain of calls on the same kind of object, as in a builder or a collection pipeline, does not reach through to strangers.
Solution
Refactoring gives two moves.1 The catalogue at refactoring.com has a card for each refactoring.3
- Hide the path: Hide Delegate. Add a method to the first object that returns the result of the chain, and change the clients to call it. The method can live at any link in the chain.
- Move the use: look at what the client does with the final object. Often it is better to use Extract Function on the code that uses the result, and then Move Function to push that code into the chain. Then the client asks for the answer, not for the object.
The first edition of Refactoring gives the same two moves.4
Refactoring warns that Hide Delegate on every link in a chain can turn the objects in between into middle men.1 The aim is to answer the client's question, not to wrap each getter.
Example
Two functions find the country that an order ships to by walking from the order to the customer to the address. Then the business adds a delivery address on the order, which wins over the customer's address. The second version changes one method; the first version would need each client to learn the rule.
import assert from "node:assert/strict";
class Address {
constructor(country) { this.country = country; }
}
class Customer {
constructor(address) { this.address = address; }
}
class Order {
constructor(customer, delivery = null) {
this.customer = customer;
this.delivery = delivery;
}
// After: the order answers the question, and knows the path.
shipsTo() {
return (this.delivery ?? this.customer.address).country;
}
}
// Before: each client walks the chain.
const taxRegionBefore = (order) => (order.customer.address.country === "DE" ? "EU" : "other");
const carrierBefore = (order) => (order.customer.address.country === "US" ? "ups" : "dhl");
// After: each client asks the order.
const taxRegion = (order) => (order.shipsTo() === "DE" ? "EU" : "other");
const carrier = (order) => (order.shipsTo() === "US" ? "ups" : "dhl");
const home = new Order(new Customer(new Address("DE")));
assert.equal(taxRegionBefore(home), taxRegion(home));
assert.equal(carrierBefore(home), carrier(home));
// A gift order ships to another country than the customer lives in.
const gift = new Order(new Customer(new Address("DE")), new Address("US"));
assert.equal(carrierBefore(gift), "dhl"); // the chain still reads the customer's address
assert.equal(carrier(gift), "ups");
assert.equal(taxRegion(gift), "other");
console.log("shipsTo: tests pass");
shipsTo: tests pass
In the second version the rule for the delivery address is in shipsTo, and every client follows it without an edit. In the first version each client that walks the chain is wrong for a gift order until someone finds and fixes it.
| Language | What the example shows |
|---|---|
| JavaScript | a method on the first object of the chain, as above |
| Python | the same method, as a property |
| Java | order.getCustomer().getAddress().getCountry() replaced by order.shipsTo() |
| Go | a method on the order struct, with the same rule |
from dataclasses import dataclass
@dataclass
class Address:
country: str
@dataclass
class Customer:
address: Address
@dataclass
class Order:
customer: Customer
delivery: Address | None = None
# After: the order answers the question, and knows the path.
@property
def ships_to(self):
return (self.delivery or self.customer.address).country
# Before: each client walks the chain.
def carrier_before(order):
return "ups" if order.customer.address.country == "US" else "dhl"
# After: each client asks the order.
def carrier(order):
return "ups" if order.ships_to == "US" else "dhl"
home = Order(Customer(Address("DE")))
assert carrier_before(home) == carrier(home) == "dhl"
gift = Order(Customer(Address("DE")), delivery=Address("US"))
assert carrier_before(gift) == "dhl" # the chain still reads the customer's address
assert carrier(gift) == "ups"
print("ships_to: tests pass")
ships_to: tests pass
@propertylets clients writeorder.ships_towith no parentheses, so the call reads like a field, but the path is still hidden in one method.Address | Nonein the annotation says that an order may have no delivery address. Theorpicks the customer's address in that case.
public class Main {
record Address(String country) {}
record Customer(Address address) {}
static final class Order {
private final Customer customer;
private final Address delivery;
Order(Customer customer, Address delivery) {
this.customer = customer;
this.delivery = delivery;
}
Customer getCustomer() { return customer; }
// After: the order answers the question, and knows the path.
String shipsTo() {
return (delivery != null ? delivery : customer.address()).country();
}
}
// Before: the client walks the chain.
static String carrierBefore(Order order) {
return order.getCustomer().address().country().equals("US") ? "ups" : "dhl";
}
// After: the client asks the order.
static String carrier(Order order) {
return order.shipsTo().equals("US") ? "ups" : "dhl";
}
public static void main(String[] args) {
Order home = new Order(new Customer(new Address("DE")), null);
if (!carrierBefore(home).equals(carrier(home))) throw new AssertionError("home");
Order gift = new Order(new Customer(new Address("DE")), new Address("US"));
if (!carrierBefore(gift).equals("dhl")) throw new AssertionError("before"); // reads the customer's address
if (!carrier(gift).equals("ups")) throw new AssertionError("after");
System.out.println("shipsTo: tests pass");
}
}
shipsTo: tests pass
order.getCustomer().address().country()has three dots afterorder, and each one is a type the client must know.order.shipsTo()has one.- Once no client calls
getCustomerto reach the address, the getter may not be needed at all, and the customer becomes a detail of the order.
package main
import "fmt"
type Address struct{ Country string }
type Customer struct{ Address Address }
type Order struct {
Customer Customer
Delivery *Address
}
// After: the order answers the question, and knows the path.
func (o Order) ShipsTo() string {
if o.Delivery != nil {
return o.Delivery.Country
}
return o.Customer.Address.Country
}
// Before: the client walks the chain.
func carrierBefore(o Order) string {
if o.Customer.Address.Country == "US" {
return "ups"
}
return "dhl"
}
// After: the client asks the order.
func carrier(o Order) string {
if o.ShipsTo() == "US" {
return "ups"
}
return "dhl"
}
func main() {
home := Order{Customer: Customer{Address{"DE"}}}
if carrierBefore(home) != carrier(home) {
panic("home")
}
gift := Order{Customer: Customer{Address{"DE"}}, Delivery: &Address{"US"}}
if carrierBefore(gift) != "dhl" { // reads the customer's address
panic("before")
}
if carrier(gift) != "ups" {
panic("after")
}
fmt.Println("ShipsTo: tests pass")
}
ShipsTo: tests pass
- In Go, a chain of exported fields is as common as a chain of getters.
o.Customer.Address.Countrycouples the client to two struct layouts. Deliveryis a pointer, sonilmeans that the order has no delivery address of its own.
Consequences
The clients know one object and one method. The path between the objects can change, and only the method that hides it must change too.
The cost is one more method on the first object for each question. Wikipedia notes that the Law of Demeter "may result in having to write many wrapper methods to propagate calls to components".2 If the first object gets a wrapper for each field of each object behind it, it becomes a Middle Man, which is the opposite smell. The balance is to add methods for the questions that clients ask, not for each getter.
A chain is not always a smell. The rule is about reaching through objects to their parts. A pipeline such as list.filter(f).map(g) calls methods on values of the same kind, and a fluent builder returns the same builder from each call; neither one exposes the structure of other objects. Data that is plain data, such as a parsed JSON document, has no behaviour to hide the path behind, and walking it is the normal use.
How to fix it
- A client that walks a chain to get one value: Hide Delegate on the first object.1
- A client that walks a chain and then computes with the result: Extract Function on the computation, then Move Function into the chain.1
- Wrappers on every link: see Middle Man and Remove Middle Man.1
Variants and related patterns
Middle Man. The opposite smell, and the risk of too much Hide Delegate. See Middle Man.
Feature Envy. A client that walks a chain often does so to compute with the data at the end. Moving the computation removes both smells. See Feature Envy.
Law of Demeter. The design guideline that limits which objects a method should call. See Law of Demeter.
References
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Message Chains
- Wikipedia, Law of Demeter, revision 1306566666, the introduction, In object-oriented programming, and Disadvantages
- Martin Fowler, Catalog of Refactorings, the cards Hide Delegate, Extract Function and Move Function
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Message Chains
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag B7P2X3 Edit this page History Report an error Markdown