Skip to content
Katabench
Try free

Stop the Train Wreck

Easy About 15 min Free, no account needed

A label printer reaches order.Buyer.HomeAddress.City to print one line, coupling itself to three classes for one string. Ask the order directly and talk to one neighbor, not a chain of strangers. Shortening the chain with a local variable does not shorten the coupling.

The brief

The shipping label printer needs exactly one string: the city an order ships to. To get it, Shipping.LabelPrinter rides a chain through the whole object graph: order.Buyer.HomeAddress.City. That one line couples the printer to three classes. Rename HomeAddress, restructure Customer, move the city onto a Delivery object, and the printer breaks, even though nothing about printing labels changed. This is the Law of Demeter, sometimes called "don't talk to strangers": a method should talk to its direct collaborators, not to the neighbors of its neighbors.

The trap

The tempting fix is cosmetic. Break the chain into local variables:

C#
var buyer = order.Buyer;
var address = buyer.HomeAddress;
return "Ship to: " + address.City;

One dot per line now, but the printer still names Customer and Address, so the coupling is byte-for-byte the same and both "talks to a stranger" rules stay red. Demeter is not about counting dots. It is about counting the types you depend on.

Your job

Let the printer ask the order one question. Give Order a way to answer "what city does this ship to?" by asking its own Buyer, which asks its own HomeAddress. Each class talks only to its direct neighbor, and the printer talks only to Order. Seal the printer while you are in there; nothing is meant to subclass it. The output must stay identical.

How it's graded

Your submission must (1) still pass the behavior tests (same label text) and (2) satisfy every rule shown in the results: LabelPrinter references neither Customer nor Address, is sealed, and Order itself never reaches past its buyer to Address. The local-variable rewrite clears nothing, and neither does moving the whole chain into Order; only letting each class ask its own neighbor turns the rules green.

Each unit should only talk to its friends. When you find yourself reaching through one object to get to another, the method you are writing is in the wrong place, or the question you are asking belongs on the first object in the chain.

How it is graded

Executable structural checks grade the shape of your types as well as their behavior.

SOLID principles exercises →

What it practices

Encapsulation
Protect invariants: no exposed mutable collections, shared static state or train-wreck navigation.

Related katas