Skip to content

Closed Hierarchies

The Course
•
25 min study

The job runner's Outcome has exactly four cases: succeeded, failed, timed out or cancelled. Such "one of these" types are everywhere, and they're known as sum types or discriminated unions. C# has no built-in syntax for them yet, but sealed records get you most of the way there.

Open versus closed

Inheritance normally leaves a type open: anyone can derive a new case. That's right for plugins, but wrong for a fixed set of states. A private constructor closes it, because only code inside the base type can call that constructor. So the ordinary way to derive a new case, calling the base constructor, works only for nested types.

Only nested cases can exist C#
Payment[] payments = { new Payment.Card("1234"), new Payment.Cash() };

foreach (Payment payment in payments)
{
    Console.WriteLine(payment);
}

abstract record Payment
{
    private Payment()
    {
    }

    public sealed record Card(string Last4) : Payment;

    public sealed record Cash() : Payment;
}
Check your prediction
Text
Card { Last4 = 1234 }
Cash { }

Try adding record Cheque() : Payment; at the end of the file. The compiler refuses it with error CS0122: the constructor is inaccessible.

There's one gap, and it comes from records. A record that isn't sealed gets a copy constructor, protected Payment(Payment original), which with uses. The compiler requires it to be protected or public (error CS8878 if you make it private), so a determined outsider can derive by calling it:

The copy constructor is still open C#
Payment payment = new Cheque(new Payment.Cash());
Console.WriteLine(payment);

abstract record Payment
{
    private Payment()
    {
    }

    public sealed record Card(string Last4) : Payment;

    public sealed record Cash() : Payment;
}

record Cheque : Payment
{
    public Cheque(Payment copyFrom) : base(copyFrom)
    {
    }
}
Check your prediction
Text
Cheque { }

So the private constructor closes a record hierarchy against accidents, not against someone working around it on purpose. That's usually enough inside one project, and it's why the switch below still throws on an unknown case. If a library must guarantee the set of cases, make the base an abstract class with a private constructor: a class has no copy constructor, so nested types really are the only ones (the cases are then classes too, because a record can't derive from a class).

The switch still needs a default

Today's compiler doesn't use that private constructor to reason about your cases, so a switch over a closed hierarchy still needs a _ arm, or you'll get warning CS8509. Don't let that arm hide problems: throw, using UnreachableException to say "this can only be a bug".

Handle all the cases, and throw otherwise C#
using System.Diagnostics;

Console.WriteLine(Fee(new Payment.Card("1234")));
Console.WriteLine(Fee(new Payment.Cash()));

static decimal Fee(Payment payment) => payment switch
{
    Payment.Card => 0.30m,
    Payment.Cash => 0m,
    _ => throw new UnreachableException(),
};

abstract record Payment
{
    private Payment()
    {
    }

    public sealed record Card(string Last4) : Payment;

    public sealed record Cash() : Payment;
}
Check your prediction
Text
0.30
0

Enums get no such help either: any int can be cast to one, so a switch over an enum has the same need. Records also carry different data per case, which enums can't do.

Make wrong states impossible

A class with flags and nullable fields allows nonsense: a Failed with an output and no error. A hierarchy can only represent real states, and the data is present exactly when it applies. Compare the two approaches.

The bad state can't be written C#
#nullable enable

var loose = new LooseOutcome { Success = true, Error = "disk full" };
Console.WriteLine(loose.Success ? loose.Output?.Length ?? -1 : 0);

Outcome tight = new Outcome.Done("hello");
Console.WriteLine(tight switch
{
    Outcome.Done done => done.Output.Length,
    Outcome.Failed failed => failed.Error.Length,
    _ => throw new InvalidOperationException(),
});

class LooseOutcome
{
    public bool Success { get; init; }
    public string? Output { get; init; }
    public string? Error { get; init; }
}

abstract record Outcome
{
    private Outcome()
    {
    }

    public sealed record Done(string Output) : Outcome;

    public sealed record Failed(string Error) : Outcome;
}
Check your prediction
Text
-1
5

There's no need for null checks with the Done case, as the Output is guaranteed to be there.

Where to put behaviour

Two designs compete here. A virtual method on each case makes it easy to add a case, because the compiler tells you what's missing. A switch in the caller makes it easy to add an operation, with no change to the types. For a closed set of data cases with many operations, a switch usually fits; for an open set of behaviours, a method or interface usually fits.

The same thing, two ways C#
Shape shape = new Shape.Square(3);

Console.WriteLine(shape.Area());
Console.WriteLine(Describe(shape));

static string Describe(Shape shape) => shape switch
{
    Shape.Square square => $"side {square.Side}",
    Shape.Circle circle => $"radius {circle.Radius}",
    _ => throw new InvalidOperationException(),
};

abstract record Shape
{
    private Shape()
    {
    }

    public abstract double Area();

    public sealed record Square(double Side) : Shape
    {
        public override double Area() => Side * Side;
    }

    public sealed record Circle(double Radius) : Shape
    {
        public override double Area() => Math.PI * Radius * Radius;
    }
}
Check your prediction
Text
9
side 3

Your turn

Exercise

A request's states

Model an HTTP-like request's state as a closed hierarchy: Pending, Sending(int Attempt), Received(int Status, string Body) and Abandoned(string Reason). Write Next(RequestState state), a switch that returns the next state:

  • Pending becomes Sending(1).
  • Sending with attempt 3 or over becomes Abandoned("too many attempts").
  • Any other Sending becomes a Sending with the next attempt.
  • A finished state returns itself.

Starting from Pending, print each state as you call Next five times. Also print Next(new Received(200, "ok")).

When it works, it prints the lines below. Each Name { … } line is a record's built-in ToString, so print the record itself rather than formatting it:

Text
Pending { }
Sending { Attempt = 1 }
Sending { Attempt = 2 }
Sending { Attempt = 3 }
Abandoned { Reason = too many attempts }
Abandoned { Reason = too many attempts }
Received { Status = 200, Body = ok }
Your workspace C#
Console.WriteLine("Start here");
Hint 1: the idea

A state machine is a single function from one state to the next. Pattern arms read almost exactly like the rules in the brief.

Hint 2: a first step

Declare the hierarchy, then write Pending and the _ arm. Remember that a more specific pattern has to come before a general one. A property pattern such as { Attempt: >= 3 } gives the limit.

Show one solution
C#
using System.Diagnostics;

RequestState state = new RequestState.Pending();
Console.WriteLine(state);
for (int i = 0; i < 5; i++)
{
    state = Next(state);
    Console.WriteLine(state);
}
Console.WriteLine(Next(new RequestState.Received(200, "ok")));

static RequestState Next(RequestState state) => state switch
{
    RequestState.Pending => new RequestState.Sending(1),
    RequestState.Sending { Attempt: >= 3 } => new RequestState.Abandoned("too many attempts"),
    RequestState.Sending sending => new RequestState.Sending(sending.Attempt + 1),
    RequestState.Received or RequestState.Abandoned => state,
    _ => throw new UnreachableException(),
};

abstract record RequestState
{
    private RequestState()
    {
    }

    public sealed record Pending() : RequestState;

    public sealed record Sending(int Attempt) : RequestState;

    public sealed record Received(int Status, string Body) : RequestState;

    public sealed record Abandoned(string Reason) : RequestState;
}
Text
Pending { }
Sending { Attempt = 1 }
Sending { Attempt = 2 }
Sending { Attempt = 3 }
Abandoned { Reason = too many attempts }
Abandoned { Reason = too many attempts }
Received { Status = 200, Body = ok }

Was this article helpful?

Your response is saved on this device.