Skip to content
Katabench
Try free

Make It a Value Object

Hard About 30 min Free, no account needed

A Reservation is a mutable two-phase DTO that also hands out its backing guest list. Make it a real value object, frozen at construction, and don't let the obvious private set fix fool you into leaving the collection leak wide open.

The brief

You've inherited a Reservation. It's supposed to be a value object: a Start, an End, a Seats count, and the Guests on the booking, all validated once and then frozen. It isn't.

Today it's a mutable, two-phase DTO. A caller does new Reservation(), sets Start, End, and Seats through public setters, and the only invariant (Start <= End) lives in a separate Validate() they have to remember to call. Nothing stops a half-built or invalid reservation from existing, and nothing stops a setter from changing one later.

It also leaks its backing list. Guests is typed List<Guest> and hands out the live collection by reference, so any caller can reservation.Guests.Add(...) (or .Clear()) and mutate the "value" long after it was supposedly fixed.

The behavior tests pass only because the harness happens to assign the fields in a valid order before reading them. The type is correct by luck, not by construction.

The obvious move backfires

The reflex fix is to add a constructor and change the properties to { get; private set; }. That looks frozen, and it does silence the "no public setter" complaint. But it doesn't make the type immutable, and it does nothing about the guest list. A reservation built that way is still mutable in ways the rules will catch, and one of those rules has nothing to do with setters at all. The half measure clears one symptom and leaves the others standing.

Your job

Make Reservation a real value object so it passes every rule, not just the easy one:

  • there is no way to build an invalid reservation (the Start <= End check happens once, at construction),
  • there is no way to mutate one after it exists, neither its scalar state nor its guest list,
  • the type is sealed.

Keep the type named Reservation, keep Run returning the same "Reservation ..." string, and keep the behavior tests green: same inputs, byte-identical output.

A value object is defined by what you can't do to it. private set narrows the door; it doesn't close it. Find the one rule the setter fix can't touch and let it tell you what "frozen" 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

Value objects
Immutable types with value equality, including strongly typed identifiers.
Encapsulation
Protect invariants: no exposed mutable collections, shared static state or train-wreck navigation.

Do these first

Related katas