Skip to content

Protecting an Object's Rules

The Course
•
25 min study

If any code can set any property to any value, then every part of the program has to be careful about what it writes. Encapsulation moves that responsibility into the class. The class controls how its data changes, so its rules hold no matter who calls it. A rule that must always hold is called an invariant.

Controlling changes

{ get; private set; } lets everyone read a property, but only the class itself can change it. Outside code has to go through a method, and that method gets to say no. A private field is data that's completely hidden from the outside.

The class refuses a bad change C#
var progress = new Progress(100);

Console.WriteLine(progress.Add(30));
Console.WriteLine(progress.Add(-5));
Console.WriteLine(progress.Add(80));
Console.WriteLine(progress.Done);

class Progress
{
    private readonly int goal;

    public int Done { get; private set; }

    public Progress(int goal)
    {
        this.goal = goal;
    }

    public bool Add(int minutes)
    {
        if (minutes < 1 || Done + minutes > goal)
        {
            return false;
        }
        Done += minutes;
        return true;
    }
}
Check your prediction
Text
True
False
False
30

Add progress.Done = 500; on a new line and read the compiler error. The rule has become something the compiler enforces. this.goal means "the field on this object", which tells it apart from the parameter with the same name. readonly means the value is set in the constructor and never again.

Computed properties

A property doesn't have to store anything. => defines one that is calculated each time it's read. That removes a whole class of bug, where a stored total drifts out of step with the data it summarizes.

Worked out when read C#
var book = new Book(200);
book.Read(50);
Console.WriteLine(book.PagesLeft);
Console.WriteLine(book.Finished);

book.Read(150);
Console.WriteLine(book.PagesLeft);
Console.WriteLine(book.Finished);

class Book
{
    public int Pages { get; }
    public int PagesRead { get; private set; }

    public int PagesLeft => Pages - PagesRead;
    public bool Finished => PagesLeft == 0;

    public Book(int pages)
    {
        Pages = pages;
    }

    public void Read(int pages)
    {
        PagesRead = Math.Min(Pages, PagesRead + pages);
    }
}
Check your prediction
Text
150
False
0
True

A property with only { get; } can be set by the constructor and nothing else. Math.Min returns the smaller of two numbers, which keeps PagesRead from going past the end of the book.

When a constructor can't succeed

A method can return false to refuse. A constructor has nothing to return, and it would be wrong to leave a half-valid object around. The standard answer is to throw an exception, which stops the creation entirely. You'll learn to catch these on Day 6; for now, see what one looks like.

Refusing to exist C#
var good = new Session(25);
Console.WriteLine(good.Minutes);

var bad = new Session(0);
Console.WriteLine(bad.Minutes);

class Session
{
    public int Minutes { get; }

    public Session(int minutes)
    {
        if (minutes < 1)
        {
            throw new ArgumentOutOfRangeException(nameof(minutes), "must be at least 1");
        }
        Minutes = minutes;
    }
}
Check your prediction
Text
25
Unhandled exception. System.ArgumentOutOfRangeException: must be at least 1

The last Console.WriteLine never ran, because bad never came into existence. So code that has a Session knows its minutes are valid and doesn't need to check. That's the payoff.

Your turn

Exercise

A water tracker with rules

Write a class WaterTracker for a daily goal in glasses. The constructor takes the goal, and throws ArgumentOutOfRangeException if it's below 1, with the message must be at least 1 and the parameter's name, nameof(goal). A method Drink(int glasses) returns false and changes nothing if glasses is below 1; otherwise it adds them and returns true. A read-only Glasses property exposes the count, and a computed Reached property says whether the goal has been met.

For a goal of 8, print the result of drinking 5, the result of trying to drink 0, and Reached. Then print the result of drinking 3, then Glasses, and Reached again. Finally, as the last two lines of the program, create new WaterTracker(0) and print its Glasses, and read the exception the program stops with. It should print:

Text
True
False
False
True
8
True
Unhandled exception. System.ArgumentOutOfRangeException: must be at least 1 (Parameter 'goal')
Your workspace C#
Console.WriteLine("Put your class under this line");
Hint 1: the idea

Glasses is changed only by Drink, so private set keeps the rule in one place. Reached is worked out from Glasses, so it can't drift.

Hint 2: a first step

Write the class with Glasses and Drink first, ignoring the goal, and check that a value of 0 is refused.

Show one solution
C#
var tracker = new WaterTracker(8);

Console.WriteLine(tracker.Drink(5));
Console.WriteLine(tracker.Drink(0));
Console.WriteLine(tracker.Reached);
Console.WriteLine(tracker.Drink(3));
Console.WriteLine(tracker.Glasses);
Console.WriteLine(tracker.Reached);

var impossible = new WaterTracker(0);
Console.WriteLine(impossible.Glasses);

class WaterTracker
{
    private readonly int goal;

    public int Glasses { get; private set; }

    public bool Reached => Glasses >= goal;

    public WaterTracker(int goal)
    {
        if (goal < 1)
        {
            throw new ArgumentOutOfRangeException(nameof(goal), "must be at least 1");
        }
        this.goal = goal;
    }

    public bool Drink(int glasses)
    {
        if (glasses < 1)
        {
            return false;
        }
        Glasses += glasses;
        return true;
    }
}
Text
True
False
False
True
8
True
Unhandled exception. System.ArgumentOutOfRangeException: must be at least 1 (Parameter 'goal')

The two kinds of bad input are handled differently on purpose. A bad drink is an ordinary event, so Drink returns false and the tracker carries on. A bad goal would make the whole object meaningless, so the constructor throws and the object is never created: the last Console.WriteLine doesn't run. Glasses has a private set, so only Drink can change it, and Reached is computed from it each time, so the two can't disagree.

Compare this with the Book class from the previous lesson, where anything could set any property. Which mistakes are now impossible, and which are still possible?

Was this article helpful?

Your response is saved on this device.