A method that returns null on failure can't say why. A method that throws makes every normal failure look exceptional, and nothing in its signature warns the caller. A third option is to make failure a normal return value. This is the design the tracker uses for Add, Complete and Load.
The shape
Result<T> is an abstract record with two cases. The caller can't reach the value without first checking which case it has, so forgetting the failure is hard.
foreach (string text in new[] { "42", "abc" })
{
string message = ParseAge(text) switch
{
Ok<int> ok => $"age {ok.Value}",
Fail<int> fail => $"error: {fail.Error}",
_ => throw new InvalidOperationException("unknown result"),
};
Console.WriteLine(message);
}
static Result<int> ParseAge(string text)
{
if (!int.TryParse(text, out int age))
{
return new Fail<int>($"{text} is not a number");
}
return new Ok<int>(age);
}
abstract record Result<T>;
sealed record Ok<T>(T Value) : Result<T>;
sealed record Fail<T>(string Error) : Result<T>;Check your prediction
age 42
error: abc is not a numberChaining steps
Real work has several steps, and the first failure should stop the rest. A helper method does it once, so you don't repeat the same check. Then is generic: it runs the next step on success, and on failure passes the error along unchanged.
foreach (string text in new[] { "20", "abc", "-1" })
{
Result<int> result = Then(ParseAge(text), Validate);
Console.WriteLine(result);
}
static Result<TOut> Then<TIn, TOut>(Result<TIn> result, Func<TIn, Result<TOut>> next)
{
return result switch
{
Ok<TIn> ok => next(ok.Value),
Fail<TIn> fail => new Fail<TOut>(fail.Error),
_ => throw new InvalidOperationException("unknown result"),
};
}
static Result<int> ParseAge(string text)
{
return int.TryParse(text, out int age) ? new Ok<int>(age) : new Fail<int>("not a number");
}
static Result<int> Validate(int age)
{
return age >= 0 ? new Ok<int>(age) : new Fail<int>("negative");
}
abstract record Result<T>;
sealed record Ok<T>(T Value) : Result<T>;
sealed record Fail<T>(string Error) : Result<T>;Check your prediction
Ok { Value = 20 }
Fail { Error = not a number }
Fail { Error = negative }Result or exception?
| Situation | Choose |
|---|---|
| The input may well be wrong, and the caller will respond | Result |
| A bug, or a broken promise in the code | Exception |
| A disk or network failure far from anyone who can respond | Exception, converted to a Result at a useful boundary |
The tracker uses this last row: JsonFileStore throws, and Tracker.Load catches at the boundary, returning a Result.
Fix it: A failure that turned into success
This version of Then has a bug in its failure arm. Predict the three lines, then run it.
foreach (string text in new[] { "20", "abc", "-1" })
{
Console.WriteLine(Then(ParseAge(text), Validate));
}
static Result<TOut> Then<TIn, TOut>(Result<TIn> result, Func<TIn, Result<TOut>> next)
{
return result switch
{
Ok<TIn> ok => next(ok.Value),
Fail<TIn> => next(default!),
_ => throw new InvalidOperationException("unknown result"),
};
}
static Result<int> ParseAge(string text)
{
return int.TryParse(text, out int age) ? new Ok<int>(age) : new Fail<int>("not a number");
}
static Result<int> Validate(int age)
{
return age >= 0 ? new Ok<int>(age) : new Fail<int>("negative");
}
abstract record Result<T>;
sealed record Ok<T>(T Value) : Result<T>;
sealed record Fail<T>(string Error) : Result<T>;Check your prediction
Ok { Value = 20 }
Ok { Value = 0 }
Fail { Error = negative }abc comes out as Ok { Value = 0 }. On failure, Then ran the next step anyway, with default (0 for an int) standing in for the missing value, so a parse error became a valid age. Fix the failure arm.
Fix it
On failure, don't call next at all. Pass the error along in a Fail of the new type:
foreach (string text in new[] { "20", "abc", "-1" })
{
Console.WriteLine(Then(ParseAge(text), Validate));
}
static Result<TOut> Then<TIn, TOut>(Result<TIn> result, Func<TIn, Result<TOut>> next)
{
return result switch
{
Ok<TIn> ok => next(ok.Value),
Fail<TIn> fail => new Fail<TOut>(fail.Error),
_ => throw new InvalidOperationException("unknown result"),
};
}
static Result<int> ParseAge(string text)
{
return int.TryParse(text, out int age) ? new Ok<int>(age) : new Fail<int>("not a number");
}
static Result<int> Validate(int age)
{
return age >= 0 ? new Ok<int>(age) : new Fail<int>("negative");
}
abstract record Result<T>;
sealed record Ok<T>(T Value) : Result<T>;
sealed record Fail<T>(string Error) : Result<T>;Ok { Value = 20 }
Fail { Error = not a number }
Fail { Error = negative }This is the bug a result type exists to prevent, and it slipped back in through a single helper. That's why Then is written once and checked, rather than repeated at every call.
Build it yourself
A bank account with results
Using Result, Ok and Fail, write a class Account with a Balance, starting from 0. Deposit(decimal amount) fails with amount must be positive for zero or below. Withdraw(decimal amount) fails in the same way, or with insufficient funds when the amount exceeds the balance. Both return the new balance on success, and a failure leaves the balance unchanged.
Using a helper Show that takes a result and prints either balance 50 or error: ..., deposit 100, withdraw 30, withdraw 500, and deposit -5. Then print the final balance.
When it works, it prints:
balance 100
balance 70
error: insufficient funds
error: amount must be positive
70Console.WriteLine(new Ok<int>(1));
abstract record Result<T>;
sealed record Ok<T>(T Value) : Result<T>;
sealed record Fail<T>(string Error) : Result<T>;Hint 1: the idea
Check everything first, and change the balance only on the last line before returning Ok. A failed call then can't leave a partial change.
Hint 2: a first step
Write Show first with a switch on the two cases and try it with a hand-made Ok. Then write Deposit, which has only one rule.
Show one solution
var account = new Account();
Show(account.Deposit(100m));
Show(account.Withdraw(30m));
Show(account.Withdraw(500m));
Show(account.Deposit(-5m));
Console.WriteLine(account.Balance);
static void Show(Result<decimal> result)
{
Console.WriteLine(result switch
{
Ok<decimal> ok => $"balance {ok.Value}",
Fail<decimal> fail => $"error: {fail.Error}",
_ => throw new InvalidOperationException("unknown result"),
});
}
class Account
{
public decimal Balance { get; private set; }
public Result<decimal> Deposit(decimal amount)
{
if (amount <= 0m)
{
return new Fail<decimal>("amount must be positive");
}
Balance += amount;
return new Ok<decimal>(Balance);
}
public Result<decimal> Withdraw(decimal amount)
{
if (amount <= 0m)
{
return new Fail<decimal>("amount must be positive");
}
if (amount > Balance)
{
return new Fail<decimal>("insufficient funds");
}
Balance -= amount;
return new Ok<decimal>(Balance);
}
}
abstract record Result<T>;
sealed record Ok<T>(T Value) : Result<T>;
sealed record Fail<T>(string Error) : Result<T>;balance 100
balance 70
error: insufficient funds
error: amount must be positive
70Expected problems, such as too little money or a bad amount, come back as Fail values, and the caller must look at the result to get the balance. Each method checks everything before it changes Balance, so a failed withdrawal leaves the account as it was, which is why the final balance is still 70. The private set makes Deposit and Withdraw the only way to change the balance.
Completion is saved in this browser only. It does not measure mastery.