LLearnCode
Academy/csharp/Model state deliberately

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.

Loading progressEvidence grows with practice
Useful preparation · 1 prerequisite

Use this as a map, not a lock. If these ideas are familiar, continue.

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.

  1. A C# class explicitly implements an interface and supplies its required members.
  2. A caller accepting the interface can work with different conforming implementations.
  3. Constructor parameters can make a dependency visible and replaceable in tests.
  4. A base class shares implementation and a subtype relationship; an interface expresses a contract. Composition can avoid a fragile hierarchy of unrelated variants.
Read the codecsharp · educational example
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);
}
  1. Contract

    The caller relies on Apply(int), not a particular shield's private details.

  2. Implementation

    FlatShield removes two damage while keeping the result nonnegative.

  3. 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 →