Immutability: value objects instead of setters
Share small objects like prices safely, so one change never leaks into another.
Watch the narrated video
Every step
Problem
Steps 1–3Refactor
Steps 4–6Payoff
Steps 7–8C# bonus
Step 9Recap
Steps 10–11The code: before and after
Before
class Price
{
public int Amount { get; private set; }
public string Currency { get; private set; }
public Price(int amount, string currency)
{
Amount = amount;
Currency = currency;
}
public void SetAmount(int amount) => Amount = amount;
}
class Booking
{
private readonly string car;
private Price price;
public Booking(string car, Price price)
{
this.car = car;
this.price = price;
}
public string Line() =>
$"{car}: {price.Amount} {price.Currency}";
public bool SameRateAs(Booking other) =>
price == other.price;
}
static class Desk
{
public static void Main()
{
var weekend = new Price(120, "USD");
var ana = new Booking("Golf", weekend);
var ben = new Booking("Polo", weekend);
Console.WriteLine(ana.Line());
Console.WriteLine(ben.Line());
Console.WriteLine(ana.SameRateAs(ben));
}
}After
record Price(int Amount, string Currency)
{
public Price Plus(int extra) =>
new Price(Amount + extra, Currency);
}
class Booking
{
private readonly string car;
private Price price;
public Booking(string car, Price price)
{
this.car = car;
this.price = price;
}
public string Line() =>
$"{car}: {price.Amount} {price.Currency}";
public bool SameRateAs(Booking other) =>
price.Equals(other.price);
public void AddExtra(int extra) =>
price = price.Plus(extra);
}
static class Desk
{
public static void Main()
{
var weekend = new Price(120, "USD");
var ana = new Booking("Golf", weekend);
var ben = new Booking("Polo", weekend);
ana.AddExtra(15);
Console.WriteLine(ana.Line());
Console.WriteLine(ben.Line());
Console.WriteLine(ana.SameRateAs(ben));
}
}Transcript, step by step
Problem
Step 1: One weekend rate Before
This is the same car rental desk that sent receipts last time, and today it prices bookings. A Price holds an amount and a currency with private setters, and it has a setter method, a method that changes one field, here Set Amount. A Booking holds a car and a price, prints one line, and checks whether two bookings pay the same rate by asking if they hold the same Price object. The desk makes one weekend rate and gives it to two customers, Ana and Ben, and the run prints Golf and Polo at a hundred twenty dollars each, then true. Both bookings cost the same, so making the weekend price once and passing it to both looked like the obvious choice.
Step 2: Ana adds a child seat Code smell
Ana adds a child seat for fifteen dollars. The quick way gives Booking an Add Extra method that reads the amount and sets it fifteen higher. Ana's line prints a hundred thirty five, but Ben's line prints a hundred thirty five as well, and Ben never asked for a seat.
Step 3: A shared mutable price Code smell
A mutable object is one whose fields can change after it is made, and a shared reference is two variables that point at the same object. Put them together and you get a shared mutable price, so a setter called through one booking changes the price the other booking reads. You can see it in the setter call here, in Ana's booking here, and in Ben's booking, which holds the same object, here. The bug sits in neither line alone, so to find it you have to trace every place a Price is shared. The usual workaround is to copy the Price before each change, and one forgotten copy brings the bug back.
Refactor
Step 4: Refactor first Back it out
So let's take the child seat out again. We'll refactor first, so a Price can't change under anyone, and then we'll add the seat.
Step 5: No setter, get-only Remove Setting Method
The first move is Remove Setting Method, so we delete Set Amount, and nothing called it, so the output stays the same. Both properties drop their private setters and become get-only, so the compiler stops any assignment outside the constructor. That makes Price immutable, which means its fields never change after it is made.
Step 6: Equal by value Change Reference to Value
On a class, double equals compares references, so it only said true because both bookings share one object, and two separate prices of a hundred twenty dollars would have said false. But a Price can never change now, so two prices with the same amount and currency can stand in for each other. That's a value object, a small immutable object that is equal to another when its values are equal. So the move is Change Reference to Value, and Price overrides Equals and Get Hash Code to compare the amount and the currency. Same Rate As now calls Equals, and the run still prints true. The desk still hands the same weekend price to both bookings, and now that's safe, because nobody can change it.
Payoff
Step 7: The child seat, again Payoff
Now the child seat comes back, and Price gets a Plus method that returns a new Price with the extra added. Add Extra stores that new Price in Ana's booking, and the desk calls it the same way as before. The run prints Golf at a hundred thirty five, Polo at a hundred twenty, and false, because the two rates now differ. The setter call is gone, Ana's booking now holds a new Price, and Ben's still holds the weekend one. The two weekend arguments, Ben's print line and the Same Rate As method didn't change in this step.
Step 8: Replaced, never changed Value object
A value object is never changed, only replaced. It fits here because two bookings share the weekend Price, so replacing it in Ana's booking can't reach Ben's. The booking is different, because it's an entity, an object with its own identity whose state may change. It's Ana's booking, so its price field may point somewhere new, but the Price it points at never changes.
C# bonus
Step 9: Price as a record C# bonus
Price was a whole class of get-only properties, a constructor, and a hand written Equals and Get Hash Code, all to hold two values. A C sharp record writes all of that from this one line, with properties that can't change after it's made and equality by value built in. An earlier lesson used a record to cut boilerplate, and here it also removes the hand written Equals, the part that's easiest to get wrong. Plus stays as it was, and Line still reads Amount and Currency, because the record keeps the same property names.
Recap
Step 10: Where we started, where we ended Before / after
On the left, Price had a setter, so any booking that held it could change it for everyone. Same Rate As compared references, which only worked because the bookings shared one object. On the right, Price is a record, and Plus returns a new Price instead of changing the old one. Ana's extra replaces the price in her booking only, and Same Rate As compares values.
Step 11: When to reach for it Takeaways
Reach for it when a small object, like a price, a date range or an address, is passed around and shared. Skip it when the object has its own identity, like Ana's booking, because code that holds it must see its changes, and a copy would leave it looking at the old booking. You'll spot it by a setter on an object that more than one owner holds, or by defensive copies before every change. In dot net, Date Time works this way, so Add Days returns a new date and leaves the old one alone.