Today you learned to share behaviour with a base class and to describe capabilities with an interface. This checkpoint uses both, in a design that you'll see often: each rule is a small object, and the code that uses the rules never changes when a new one arrives.
Warm up: polymorphism through an interface
Predict the output. Which line chooses the Check that runs?
var rules = new List<IRule> { new NotBlank(), new MaxLength(5) };
foreach (string input in new[] { "ok", "", "much too long" })
{
int broken = 0;
foreach (IRule rule in rules)
{
if (!rule.Check(input))
{
broken++;
}
}
Console.WriteLine($"[{input}] broke {broken}");
}
interface IRule
{
bool Check(string text);
}
class NotBlank : IRule
{
public bool Check(string text) => text.Trim().Length > 0;
}
record MaxLength(int Limit) : IRule
{
public bool Check(string text) => text.Length <= Limit;
}Check your prediction
[ok] broke 0
[] broke 1
[much too long] broke 1rule.Check(input) runs a different method for each object. Adding a third rule means writing a new class and adding it to the list. The loop stays the same.
Sharing a message with a base class
Every rule should explain itself when it fails. An abstract record can hold that message, and its Validate method can return null when the text is fine. #nullable enable lets string? state that plainly. You'll study nullable types properly on Day 4.
#nullable enable
Rule rule = new MinLength(3);
Console.WriteLine(rule.Validate("abc") ?? "fine");
Console.WriteLine(rule.Validate("ab") ?? "fine");
abstract record Rule(string Message)
{
protected abstract bool Passes(string text);
public string? Validate(string text) => Passes(text) ? null : Message;
}
record MinLength(int Limit) : Rule($"needs at least {Limit} characters")
{
protected override bool Passes(string text) => text.Length >= Limit;
}Check your prediction
fine
needs at least 3 charactersFix it: A rule that's backwards
This Rule base class should return the message only when the text fails. Predict both lines, then run it.
#nullable enable
Rule rule = new MinLength(3);
Console.WriteLine(rule.Validate("abc") ?? "fine");
Console.WriteLine(rule.Validate("ab") ?? "fine");
abstract record Rule(string Message)
{
protected abstract bool Passes(string text);
public string? Validate(string text) => Passes(text) ? Message : null;
}
record MinLength(int Limit) : Rule($"needs at least {Limit} characters")
{
protected override bool Passes(string text) => text.Length >= Limit;
}Check your prediction
needs at least 3 characters
fineEvery rule built on this base class is now wrong in the same way: good text gets the complaint, and bad text is called fine. One line in the base class is the bug, and no derived class can fix it. Find it and fix it.
Fix it
Swap the two results in Validate:
#nullable enable
Rule rule = new MinLength(3);
Console.WriteLine(rule.Validate("abc") ?? "fine");
Console.WriteLine(rule.Validate("ab") ?? "fine");
abstract record Rule(string Message)
{
protected abstract bool Passes(string text);
public string? Validate(string text) => Passes(text) ? null : Message;
}
record MinLength(int Limit) : Rule($"needs at least {Limit} characters")
{
protected override bool Passes(string text) => text.Length >= Limit;
}fine
needs at least 3 charactersShared code in a base class is powerful because one fix repairs every rule, and for the same reason one bug breaks them all. Test the base class's logic through at least one passing and one failing case.
Build it yourself
A password checker
Build these rules on the Rule base class above: MinLength(int), HasDigit and NotOneOf(params string[] banned). The last two have the messages needs a digit and is too common. Write a method Problems(string text, List<Rule> rules) that returns the messages of the broken rules, in order.
Using rules for a minimum length of 8, a digit, and a ban on password1, print each problem for the inputs short, password1 and correct7horse. Each line is the password, a colon, then its problems joined with , , or ok for a clean password.
When it works, it prints:
short: needs at least 8 characters, needs a digit
password1: is too common
correct7horse: ok#nullable enable
foreach (string input in new[] { "short", "password1", "correct7horse" })
{
Console.WriteLine(input);
}Hint 1: the idea
Problems only knows about Validate. It collects every result that isn't null, and it doesn't care which rules exist.
Hint 2: a first step
Copy Rule and MinLength from above, then write Problems with those alone. Add the other two rules one at a time. char.IsDigit tests a single character.
Show one solution
#nullable enable
var rules = new List<Rule> { new MinLength(8), new HasDigit(), new NotOneOf("password1") };
foreach (string input in new[] { "short", "password1", "correct7horse" })
{
List<string> problems = Problems(input, rules);
Console.WriteLine(problems.Count == 0 ? $"{input}: ok" : $"{input}: {string.Join(", ", problems)}");
}
static List<string> Problems(string text, List<Rule> rules)
{
var messages = new List<string>();
foreach (Rule rule in rules)
{
string? message = rule.Validate(text);
if (message is not null)
{
messages.Add(message);
}
}
return messages;
}
abstract record Rule(string Message)
{
protected abstract bool Passes(string text);
public string? Validate(string text) => Passes(text) ? null : Message;
}
record MinLength(int Limit) : Rule($"needs at least {Limit} characters")
{
protected override bool Passes(string text) => text.Length >= Limit;
}
record HasDigit() : Rule("needs a digit")
{
protected override bool Passes(string text)
{
foreach (char c in text)
{
if (char.IsDigit(c))
{
return true;
}
}
return false;
}
}
record NotOneOf(params string[] Banned) : Rule("is too common")
{
protected override bool Passes(string text) => !Banned.Contains(text);
}short: needs at least 8 characters, needs a digit
password1: is too common
correct7horse: okProblems asks every rule, rather than stopping at the first failure, so a user learns everything to fix in one go. Each rule only answers "does this pass?", and the shared base record turns that answer into a message, so the messages live next to the rules they describe. A new rule is a new record in the list; nothing else changes.
Before moving on, can you say why Problems didn't change when you added NotOneOf? That is the design goal of today. A class can't derive from a record, so NotOneOf has to be a record as well.
Completion is saved in this browser only. It does not measure mastery.