Skip to the guide

Enums, value objects and immutability

IntermediateConcept6 pages

Some objects are things with an identity, such as a customer or a bank account. Others are just values, such as a price, a cup size or a date, where any two equal ones are interchangeable. Interviewers listen for whether you model values as values: compared by what they hold, never changed after they are made, and safe to share.

Coins and a printed receipt

When you pay for a coffee, you don't care which $1 coin you get back as change, because any two are worth the same. Nobody changes a coin's value either. If your coffee costs $4 and you hand over a $5 note, you get a new coin back, and your note is still a $5 note. At the till, the cashier prints a receipt for what you ordered. You can keep writing on your own shopping list afterwards, and the receipt in your hand doesn't change. The board above the counter lists each drink's price and three cup sizes, and each size shows what it adds to the price.

In code, a coin or a note is a value object, here Money. Two with the same amount are equal, and adding two returns a new one instead of changing either. The printed receipt is an immutable object, Receipt, which can't change after it is made because it keeps its own copy of the order. That copy is called a defensive copy. Your shopping list is the caller's list, which can keep changing. The board's prices are the Menu. Its sizes are an enum, a type with a fixed list of named values, and each size knowing its own extra price is an enum with behaviour.