Message Chains

Long chains of object navigation.

“A client asks one object for another object, which asks for another.” – Fowler & Beck

a.getB().getC().getD().doSomething().

Signs of Use (Symptoms)

  • Long chains of . navigation.
  • Client knows the entire object graph structure.

Why it is bad (Consequences)

  • Fragility: If the structure changes (C no longer has D), client breaks.
  • LoD Violation: Client knows too much about internals.

Why it happens (Root Cause)

Traversing an object graph seems natural. “Just get to the thing I need.”

When it might be okay (Exceptions)

  • Fluent APIs (Builder pattern returns this).
  • DSLs.

Explanation

Problem

To get the city of a user’s address, you write user.getProfile().getAddress().getCity().

The Flaw

The client is coupled to the internal structure of User, Profile, and Address.

Real world analogy

Asking a friend: “Ask your brother to ask his wife to ask her cousin for the recipe.” Just ask the person directly.

Refactoring Solution

  • Hide Delegate: Add a shortcut method on the intermediate object (user.getCity()).

Pros and Cons (of the Antipattern)

Pros (Why people do it) Cons (The price you pay)
  • Expressive path
  • Coupling to structure
  • Comparison

    • Related Antipatterns: Middle Man (the fix can create this).
    • Related Principles: Law of Demeter.

    Code example

    Typescript

    Bad (The Antipattern)

    Good (The Fix)