I'll Be Backend
Principles · C#

Encapsulation: public fields to guarded state

Make one class own its data, so every change follows the same rules.

13 steps4 chapters~4 min at 1.25×#oop#encapsulation#private fields#getters and setters
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the C# video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–3

Refactor

Steps 4–9

Payoff

Steps 10–11

Recap

Steps 12–13

The code: before and after

Before

class GiftCard(string code, int balance)
{
    public string Code = code;
    public int Balance = balance;
}

class Checkout
{
    public void Pay(GiftCard card, int amount)
    {
        if (card.Balance >= amount)
        {
            card.Balance -= amount;
        }
    }
}

class Refunds
{
    public void Refund(GiftCard card, int amount)
    {
        card.Balance += amount;
    }
}

class Support
{
    public void Cancel(GiftCard card)
    {
        card.Balance = 0;
    }
}

class Shop
{
    static void Main()
    {
        var card = new GiftCard("GC-7", 50);
        new Checkout().Pay(card, 30);
        new Refunds().Refund(card, 10);
        new Support().Cancel(card);
        Console.WriteLine(card.Balance);
    }
}

After

class GiftCard(string code, int balance)
{
    private readonly List<string> history = new();

    public string Code = code;
    public int Balance { get; private set; } = balance;
    public IReadOnlyList<string> History => history.AsReadOnly();

    public bool Charge(int amount)
    {
        if (Balance >= amount)
        {
            Balance -= amount;
            history.Add($"paid {amount}");
            return true;
        }
        return false;
    }

    public void Credit(int amount)
    {
        Balance += amount;
        history.Add($"refunded {amount}");
    }

    public void Cancel()
    {
        history.Add($"cancelled {Balance}");
        Balance = 0;
    }
}

class Checkout
{
    public void Pay(GiftCard card, int amount)
    {
        card.Charge(amount);
    }
}

class Refunds
{
    public void Refund(GiftCard card, int amount)
    {
        card.Credit(amount);
    }
}

class Support
{
    public void Cancel(GiftCard card)
    {
        card.Cancel();
    }
}

class Shop
{
    static void Main()
    {
        var card = new GiftCard("GC-7", 50);
        new Checkout().Pay(card, 30);
        new Refunds().Refund(card, 10);
        new Support().Cancel(card);
        Console.WriteLine(card.Balance);
        Console.WriteLine(string.Join(", ", card.History));
    }
}

Transcript, step by step

Problem

Step 1: A shop's gift cards Before

A gift card here holds a code and a balance, and both are public fields. Checkout takes money off when there's enough, Refunds puts money back, and Support cancels a card by setting the balance to zero. The card starts at 50, pays 30, gets 10 back, and is cancelled, so Shop prints 0.

Step 2: Finance wants a history Code smell

Finance now needs a history of every balance change, for audits. The quick way is a public history list on the card, plus a line in Pay and a line in Refund that record each change. Shop then prints the balance, followed by the history.

Step 3: Every class writes the balance Code smell

A public field lets any class change the balance, so the rule for changing it is spread over every class that writes it. Checkout writes the balance here, Refunds here, and Support here. Support's cancel takes 30 off the card, and the history never hears of it, so the audit shows 30 left on a card that holds 0. And the funds check lives in Checkout only, so Refunds and Support write the balance with no check at all.

Refactor

Step 4: Refactor first Back it out

Let's take the history out again. We'll refactor first, so that adding the history becomes a small change, and then we'll add it.

Step 5: Balance becomes a property Encapsulate Field

First, the public field becomes a property, with a getter and a setter that C sharp writes for us. Checkout, Refunds and Support don't change, because a property reads like a field, but every write now goes through the setter. The field is hidden behind the property, but the setter is public, so any class can still set any number, and this alone guards nothing.

Step 6: Charge moves into the card Move Method

The funds check and the subtraction move into Gift Card, as a method called Charge. Charge returns true when the card had enough, and false when it didn't. Checkout now calls card dot Charge with the amount, and the card still ends at 0.

Step 7: Credit moves into the card Move Method

The refund's addition moves into Gift Card the same way, as a method called Credit. Refunds now calls card dot Credit, and it no longer reads or writes the balance itself.

Step 8: Cancel moves into the card Move Method

Support's zeroing moves in last, as Cancel, a method with no parameters. Support calls card dot Cancel, so no class outside Gift Card uses the setter any more.

Step 9: Make the setter private Remove Setting Method

Nothing outside Gift Card sets the balance now, so the setter becomes private, and the getter stays public for Shop to print. From here on, the compiler stops any class outside Gift Card that tries to write the balance. The balance now changes only inside Gift Card, through Charge, Credit and Cancel. That is encapsulation, where an object keeps its state private and offers methods for the changes it allows, so its state can only change in one place.

Payoff

Step 10: Add the history again Payoff

Now the history goes back in, as a private list inside Gift Card. Charge, Credit and Cancel each add one line to it. The History property hands out a read-only view, so callers can read the list but can't add to it, and that move is called Encapsulate Collection. Checkout, Refunds and Support didn't change, and Shop only gains a line that prints the history.

Step 11: One owner for the balance Payoff

The three writes are gone from the callers, so Checkout calls Charge here, Refunds calls Credit here, and Support calls Cancel here. Cancel now records cancelled 30 before it zeroes the card, so the history and the balance agree. And the funds check sits next to the only code that writes the balance.

Recap

Step 12: Where we started, where we ended Before / after

On the left, the balance is a public field, and Checkout, Refunds and Support each write it themselves. On the right, the setter is private, and only Charge, Credit and Cancel change the balance. A caller like Checkout makes one call, and the card decides what happens to its money.

Step 13: When to reach for it Takeaways

Reach for it when several classes change the same value and a rule must hold every time it changes. Skip it when a class only carries data with no rule, like a DTO for one view, because private setters there add lines and protect nothing. You'll spot the need by the same field assigned in many classes, or by a check copied before each write. C sharp's own List works this way, because you can read its Count, but only Add and Remove can change it.