Course contentsShow
← Computer Science
Lesson 2339 of 2,87252. Clean Code and RefactoringFree lesson

Message Chains Smell

Detect long chains of method calls (Law of Demeter violations) that create tight coupling between objects.

Message Chains Smell

What you'll learn: You'll discover how long chains of method calls create brittle code that's tightly coupled and hard to maintain.

The Problem

Imagine asking your friend to get something from their parent's car: "Go ask your mom for her keys, then unlock her car, open the glove compartment, and grab the sunglasses." That's a lot of steps through intermediaries! In code, message chains look like this:

customer.getAddress().getZipCode().getCityName()

This is called a Law of Demeter violation (also known as the "principle of least knowledge"). Your code is reaching through multiple objects to get what it wants, creating dependencies on the entire chain's structure.

Why It's Bad

When you write order.getCustomer().getAddress().getCity(), your code now depends on:

  • Order having a customer
  • Customer having an address
  • Address having a city

If any link changes (maybe Address now stores city differently), your code breaks. You're also exposing the internal structure of multiple classes, violating encapsulation.

The Smell in Action

# Message chain smell
finalPrice = cart.getItems().get(0).getProduct().getPrice().getDiscounted()

# Better: ask the object you're talking to
finalPrice = cart.getFirstItemDiscountedPrice()

The Law of Demeter says: "Only talk to your immediate friends." Don't reach through them to access their friends.

Spotting the Pattern

Look for multiple dots (.) chaining method calls together. Each additional link makes your code more fragile and harder to test—you need to mock the entire chain!

Key Takeaway: Message chains create tight coupling by exposing internal object structures; refactor by adding methods to the object you're directly working with, letting it handle the navigation internally.