Skip to content
Katabench
Try free

Freeze the Money

Medium About 15 min Free, no account needed

Money pretends to be a value object: its arithmetic returns new instances, but its Amount and Currency are still publicly settable over a mutable field. Make it structurally immutable, and don't let the reflex private set fool you; it hides the setter but leaves the backing field writable.

The brief

You've inherited a Money. It's supposed to be a value object: an Amount and a Currency, fixed at construction, so two instances with the same amount and currency are interchangeable and an amount can never change once created. It isn't.

The behavior looks fine. Add returns a brand-new Money, so the arithmetic tests pass. But the structure is a mutable bag. Amount is a public auto-property with a set, and Currency is a public property over a writable _currency field, so total.Amount = 0 is legal long after construction, silently corrupting a balance the rest of the program already trusts. The type is a value object by name only; nothing about its shape makes it one.

The obvious move backfires

The reflex fix is to change the properties to { get; private set; }. That looks frozen, and it does silence the "no public setter" complaint: callers outside the type can no longer assign Amount. But it doesn't make the type immutable. A private set still compiles to a writable backing field, so the readonly-fields rule (and the umbrella immutability rule that rolls it up) keep failing. Hiding the setter narrows the door; it doesn't close it. The half measure clears one symptom and leaves the others standing.

Your job

Make Money structurally immutable so it passes every rule, not just the easy one:

  • its observable state is fixed at construction (Amount and Currency are get-only, or init),
  • no instance field is reassignable after the constructor runs,
  • the type stays sealed.

Keep the type named Money, keep Add returning a new Money, and keep the behavior tests green: same inputs, byte-identical output.

Immutability is a property of the type, not a visibility tweak on one accessor. Find the rule the private set 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 →

Related guides

What it practices

Value objects
Immutable types with value equality, including strongly typed identifiers.

Related katas