Skip to content
Katabench
Try free

Seal the Aggregate

Hard About 25 min Free, no account needed

Order enforces a three-line cap in AddLine but hands out its backing List<OrderLine> through a public, settable property. Seal the aggregate so callers can only change it through its methods, and don't let the obvious private set fix fool you into leaving the collection leak wide open.

The brief

Order is an aggregate root. It owns its OrderLine children and is responsible for their invariants (here, a cap of at most three lines, enforced inside AddLine). The trouble is how it exposes them.

Today Lines is typed List<OrderLine> and surfaced with a public getter and a public setter. That hands every caller a direct, mutable reference to the backing collection, and lets them replace it outright. In the happy path callers go through AddLine, so the behavior tests pass. But nothing structural stops a consumer from writing order.Lines.Add(extra), order.Lines.Clear(), or order.Lines = new List<OrderLine>(), sailing straight past the cap and any other invariant the aggregate is supposed to guard. On top of that, Order isn't sealed, so a subclass could override the invariant away too. The aggregate is leaking its internals.

The obvious move backfires

The reflex fix is to hide the setter: change the property to public List<OrderLine> Lines { get; private set; } (and seal the class while you're there). That looks encapsulated, and it does silence the "no public setter" complaint and the "must be sealed" complaint. But it doesn't actually seal the aggregate. The property is still typed List<OrderLine>, so the getter still hands out the live backing collection, and order.Lines.Add(extra) still bypasses the cap. The half measure clears two symptoms and leaves the one that mattered standing, and it has nothing to do with the setter at all.

Your job

Make Order a real aggregate root so it passes every rule, not just the easy ones:

  • the children can be read but not mutated from the outside (no Add/Clear, and no setter to swap the collection out),
  • AddLine is the only way to change the order, so the three-line cap can never be bypassed,
  • the type is sealed.

Keep the type named Order, keep AddLine working, and keep the behavior tests green: same inputs, byte-identical output.

Encapsulation is about the type you expose, not the visibility of one accessor. private set narrows who can replace the list; it does nothing about who can mutate the one you already handed out. Find the rule the setter fix can't touch and let it tell you what "sealed" really means.

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