Smells of Tangling: Reaching Through Objects

When code reaches through one object to another to get an answer (booking.member().plan().price()), one small rule change touches every place that reaches, and one is always missed; the smells of tangling all come from code that knows too much about other objects, and their cures move the knowledge to where it belongs.

Journeyman · Software Development · OOP · Updated

By

After this lesson you can

  • Spot a smell of tangling in code and name its cause
  • Choose the cure for a smell of tangling: move the method, Facade, Observer, Mediator or Adapter

Key takeaways

  • The smells of tangling: a chain of calls that reaches through objects, one small change that touches many files (shotgun surgery), and a class that knows everyone.
  • Their cause: code that knows too much about how other objects are put together, so a change to one object ripples into every place that knows.
  • The plainest cure is moving the method: ask the object that has the data for the answer, instead of reaching through it.
  • Facade, Observer, Mediator and Adapter are the cures when callers know too many parts, too many listeners, each other, or another system's shape.

Before this: Smells of Choosing and Smells of Making, the first two families.

Summit Gym is starting a student discount: students pay $10 a month less, on any plan. Leo is a student on the basic plan ($30 a month), so he should pay $20. It's one rule, one number. The developer who added it last week changed the monthly bill and the receipt, and went home. On Monday Leo asked the front desk what he owes.

A doctor's clipboard chart titled "Summit Gym's booking system", with five rows, one for each family of smells: Choosing, Making, Tangling, Size and Combining, and three columns headed Symptom, Cause and Cure

The symptom: reaching through objects

A booking holds a member; a member holds a plan; a plan holds a price. Every screen that needs the price walks that path itself:

Booking booking = new Booking(new Member("Leo", new Plan("basic", 30), true), "Spin");
Console.WriteLine(FrontDesk(booking));
Console.WriteLine(MonthlyBill(booking));
Console.WriteLine(Receipt(booking));

string FrontDesk(Booking booking) =>
    quot;Front desk: {booking.Member.Name} pays ${booking.Member.Plan.Price} a month";

string MonthlyBill(Booking booking)
{
    int price = booking.Member.Plan.Price;
    if (booking.Member.Student) { price -= 10; }
    return quot;Monthly bill: {booking.Member.Name}, ${price}";
}

string Receipt(Booking booking)
{
    int price = booking.Member.Plan.Price;
    if (booking.Member.Student) { price -= 10; }
    return quot;Receipt: {booking.Member.Name} paid ${price}";
}

record Plan(string Name, int Price);
record Member(string Name, Plan Plan, bool Student);
record Booking(Member Member, string Kind);
Front desk: Leo pays $30 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20
record Plan(String name, int price) {}
record Member(String name, Plan plan, boolean student) {}
record Booking(Member member, String kind) {}

String frontDesk(Booking booking) {
    return "Front desk: " + booking.member().name() + " pays quot; + booking.member().plan().price() + " a month";
}

String monthlyBill(Booking booking) {
    int price = booking.member().plan().price();
    if (booking.member().student()) { price -= 10; }
    return "Monthly bill: " + booking.member().name() + ", quot; + price;
}

String receipt(Booking booking) {
    int price = booking.member().plan().price();
    if (booking.member().student()) { price -= 10; }
    return "Receipt: " + booking.member().name() + " paid quot; + price;
}

void main() {
    Booking booking = new Booking(new Member("Leo", new Plan("basic", 30), true), "Spin");
    IO.println(frontDesk(booking));
    IO.println(monthlyBill(booking));
    IO.println(receipt(booking));
}
Front desk: Leo pays $30 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20
from dataclasses import dataclass


@dataclass
class Plan:
    name: str
    price: int


@dataclass
class Member:
    name: str
    plan: Plan
    student: bool


@dataclass
class Booking:
    member: Member
    kind: str


def front_desk(booking):
    return f"Front desk: {booking.member.name} pays ${booking.member.plan.price} a month"


def monthly_bill(booking):
    price = booking.member.plan.price
    if booking.member.student:
        price -= 10
    return f"Monthly bill: {booking.member.name}, ${price}"


def receipt(booking):
    price = booking.member.plan.price
    if booking.member.student:
        price -= 10
    return f"Receipt: {booking.member.name} paid ${price}"


booking = Booking(Member("Leo", Plan("basic", 30), True), "Spin")
print(front_desk(booking))
print(monthly_bill(booking))
print(receipt(booking))
Front desk: Leo pays $30 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20
function frontDesk(booking) {
  return `Front desk: ${booking.member.name} pays ${booking.member.plan.price} a month`;
}

function monthlyBill(booking) {
  let price = booking.member.plan.price;
  if (booking.member.student) { price -= 10; }
  return `Monthly bill: ${booking.member.name}, ${price}`;
}

function receipt(booking) {
  let price = booking.member.plan.price;
  if (booking.member.student) { price -= 10; }
  return `Receipt: ${booking.member.name} paid ${price}`;
}

const booking = { member: { name: "Leo", plan: { name: "basic", price: 30 }, student: true }, kind: "Spin" };
console.log(frontDesk(booking));
console.log(monthlyBill(booking));
console.log(receipt(booking));
Front desk: Leo pays $30 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20
interface Plan { name: string; price: number; }
interface Member { name: string; plan: Plan; student: boolean; }
interface Booking { member: Member; kind: string; }

function frontDesk(booking: Booking): string {
  return `Front desk: ${booking.member.name} pays ${booking.member.plan.price} a month`;
}

function monthlyBill(booking: Booking): string {
  let price = booking.member.plan.price;
  if (booking.member.student) { price -= 10; }
  return `Monthly bill: ${booking.member.name}, ${price}`;
}

function receipt(booking: Booking): string {
  let price = booking.member.plan.price;
  if (booking.member.student) { price -= 10; }
  return `Receipt: ${booking.member.name} paid ${price}`;
}

const booking: Booking = { member: { name: "Leo", plan: { name: "basic", price: 30 }, student: true }, kind: "Spin" };
console.log(frontDesk(booking));
console.log(monthlyBill(booking));
console.log(receipt(booking));
Front desk: Leo pays $30 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20

Three screens, three answers to "what does Leo pay?", and the front desk's is wrong. Nobody here made a strange mistake: the rule "what a member pays" lives in every screen that reaches through booking.member.plan.price, so changing the rule meant finding each one.

  • The symptom: a message chain, booking.member().plan().price(), a line of calls that walks through one object to the next to get an answer. And a second symptom it causes: one small rule change that touches every file that walks the chain. Books on refactoring call that shotgun surgery: one shot, many small wounds.
  • The cause: the screens know too much about how other objects are put together. That's coupling, the tangled cords of Module 1: when the screens are tied to the shape of the booking, the member and the plan, a change to any of them pulls on every screen.

The rest of the family

The third smell of tangling is a class that knows everyone. The gym's front desk class calls the bookings, the waitlist, the email sender, the door lock and the loyalty points, each by name, and each of those calls some of the others back. Change one, and you have to read all of them to know what else moves. You've met its milder forms already: Pass 1's order desk calling the kitchen and the customer's phone by name, and Pass 3's devices wired to each other.

The cure: ask, don't reach

What would you try? A comment above the rule, "keep these three in step", doesn't run. One shared function priceFor(booking) that every screen calls is a real step forward. The cure goes one step further and puts that function where the data already is.

Move the method. The member knows its plan and whether it's a student, so the member answers "what do you pay a month?". The booking asks its member. Each object talks to its neighbor and no further, an old rule of thumb called the Law of Demeter ("talk to your friends, not your friends' friends"):

Booking booking = new Booking(new Member("Leo", new Plan("basic", 30), true), "Spin");
Console.WriteLine(quot;Front desk: {booking.Member.Name} pays ${booking.MonthlyPrice()} a month");
Console.WriteLine(quot;Monthly bill: {booking.Member.Name}, ${booking.MonthlyPrice()}");
Console.WriteLine(quot;Receipt: {booking.Member.Name} paid ${booking.MonthlyPrice()}");

record Plan(string Name, int Price);

record Member(string Name, Plan Plan, bool Student)
{
    // The rule lives with the data it needs.
    public int MonthlyPrice() => Student ? Plan.Price - 10 : Plan.Price;
}

record Booking(Member Member, string Kind)
{
    public int MonthlyPrice() => Member.MonthlyPrice();
}
Front desk: Leo pays $20 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20
record Plan(String name, int price) {}

record Member(String name, Plan plan, boolean student) {
    // The rule lives with the data it needs.
    int monthlyPrice() { return student ? plan.price() - 10 : plan.price(); }
}

record Booking(Member member, String kind) {
    int monthlyPrice() { return member.monthlyPrice(); }
}

void main() {
    Booking booking = new Booking(new Member("Leo", new Plan("basic", 30), true), "Spin");
    IO.println("Front desk: " + booking.member().name() + " pays quot; + booking.monthlyPrice() + " a month");
    IO.println("Monthly bill: " + booking.member().name() + ", quot; + booking.monthlyPrice());
    IO.println("Receipt: " + booking.member().name() + " paid quot; + booking.monthlyPrice());
}
Front desk: Leo pays $20 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20
from dataclasses import dataclass


@dataclass
class Plan:
    name: str
    price: int


@dataclass
class Member:
    name: str
    plan: Plan
    student: bool

    def monthly_price(self):
        """The rule lives with the data it needs."""
        return self.plan.price - 10 if self.student else self.plan.price


@dataclass
class Booking:
    member: Member
    kind: str

    def monthly_price(self):
        return self.member.monthly_price()


booking = Booking(Member("Leo", Plan("basic", 30), True), "Spin")
print(f"Front desk: {booking.member.name} pays ${booking.monthly_price()} a month")
print(f"Monthly bill: {booking.member.name}, ${booking.monthly_price()}")
print(f"Receipt: {booking.member.name} paid ${booking.monthly_price()}")
Front desk: Leo pays $20 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20
class Member {
  constructor(name, plan, student) { this.name = name; this.plan = plan; this.student = student; }
  // The rule lives with the data it needs.
  monthlyPrice() { return this.student ? this.plan.price - 10 : this.plan.price; }
}

class Booking {
  constructor(member, kind) { this.member = member; this.kind = kind; }
  monthlyPrice() { return this.member.monthlyPrice(); }
}

const booking = new Booking(new Member("Leo", { name: "basic", price: 30 }, true), "Spin");
console.log(`Front desk: ${booking.member.name} pays ${booking.monthlyPrice()} a month`);
console.log(`Monthly bill: ${booking.member.name}, ${booking.monthlyPrice()}`);
console.log(`Receipt: ${booking.member.name} paid ${booking.monthlyPrice()}`);
Front desk: Leo pays $20 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20
interface Plan { name: string; price: number; }

class Member {
  name: string;
  plan: Plan;
  student: boolean;
  constructor(name: string, plan: Plan, student: boolean) { this.name = name; this.plan = plan; this.student = student; }
  // The rule lives with the data it needs.
  monthlyPrice(): number { return this.student ? this.plan.price - 10 : this.plan.price; }
}

class Booking {
  member: Member;
  kind: string;
  constructor(member: Member, kind: string) { this.member = member; this.kind = kind; }
  monthlyPrice(): number { return this.member.monthlyPrice(); }
}

const booking = new Booking(new Member("Leo", { name: "basic", price: 30 }, true), "Spin");
console.log(`Front desk: ${booking.member.name} pays ${booking.monthlyPrice()} a month`);
console.log(`Monthly bill: ${booking.member.name}, ${booking.monthlyPrice()}`);
console.log(`Receipt: ${booking.member.name} paid ${booking.monthlyPrice()}`);
Front desk: Leo pays $20 a month
Monthly bill: Leo, $20
Receipt: Leo paid $20

All three screens agree, and none of them knows that plans exist. When the gym adds a family discount, it goes in monthlyPrice, once. The screens still read booking.member.name, one step to a neighbor, and that's fine: the trouble was never the dots, it was a rule spread across the screens.

No pattern was needed. Moving a method to the object whose data it uses is one of the plainest refactorings there is, and it cures most message chains on its own.

Which cure fits?

What's tangled The cure Where you met it
A caller reaching through objects for an answer Move the method to the object that has the data this lesson
One small change that touches many files Gather what changes together into one place: move the methods, or put a front on them this lesson; Facade: One Button, Many Parts
Every caller running the same parts, in the same order Facade: one simple front Facade: One Button, Many Parts
One object calling everyone who cares, by name Observer: a list of listeners Observer: Tell Whoever's Listening
Parts that all call each other Mediator: one hub they report to Mediator: The Hub in the Middle
Code that speaks another system's language everywhere Adapter: one translator at the border Adapter: The Interpreter Between Two Strangers
Business rules that know how the data is stored Repository Repository: Ask for the Book, Not the Shelf
Code that knows how a collection is stored, to walk it Iterator Iterator: Next Stop, Please

The smells of tangling as a symptom, cause and cure table: a chain of calls through objects (callers know how others are built; move the method); one change touching many files (one rule spread out; gather it); a class that knows everyone (Facade, Observer or Mediator)

Check yourself

2 questions to try on the lesson page.

So what

When you see a line of dots walking through objects, or a small change that needs a dozen edits, ask who already has the data, and move the rule there. Each object talks to its neighbors, and the next change has one place to go.

Key terms

Cheat sheets