intermediate · 26 minute study
Depend on the behavior you need
Swap a game's damage rule or a storage implementation without changing the code that uses the behavior.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- Records describe values, but with is a shallow copy — Choose deliberately between comparing identity and comparing a data value. Avoid assuming convenient record syntax makes nested data immutable.
First, build a mental model
An interface names a capability. Composition gives an object a collaborator that provides that capability. Inheritance is appropriate when a subtype can honor the base contract, not merely because two classes share a few lines.
- A C# class explicitly implements an interface and supplies its required members.
- A caller accepting the interface can work with different conforming implementations.
- Constructor parameters can make a dependency visible and replaceable in tests.
- A base class shares implementation and a subtype relationship; an interface expresses a contract. Composition can avoid a fragile hierarchy of unrelated variants.
IDamageRule rule = new FlatShield();
Console.WriteLine(rule.Apply(7));
Console.WriteLine(rule.Apply(1));
interface IDamageRule
{
int Apply(int incoming);
}
sealed class FlatShield : IDamageRule
{
public int Apply(int incoming) => Math.Max(0, incoming - 2);
}
sealed class NoShield : IDamageRule
{
public int Apply(int incoming) => Math.Max(0, incoming);
}- Contract
The caller relies on Apply(int), not a particular shield's private details.
- Implementation
FlatShield removes two damage while keeping the result nonnegative.
- Substitution
NoShield can be supplied through the same IDamageRule contract.
Production thinking
Take this beyond the example.
Keep interfaces near the consuming boundary. Introduce them where substitution, testing or external I/O creates a real benefit, not as a ceremonial wrapper around every method.
Sources and further reading
Your evidence
unseen is a local learning signal, not a credential or proof of production competence.
Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.
Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.
Next lesson · Generics keep a relationship intact across a reusable algorithm →