×

c# · level 3 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Hand an object what it needs instead of letting it grab it.

A class that builds its own helpers is welded to them. An OpeningHours class that reads the real clock gives a different answer every hour, so nobody can test it. The clock is a : something a class needs to do its job.

means passing dependencies in, usually through the constructor, typed as interfaces. OpeningHours asks for any IClock. The real program hands it one that reads the computer's clock. A test hands it a : a stand-in that always says the same time, so the answer can be checked.

No framework is needed. A constructor and an interface are enough.

using System;

var early = new OpeningHours(new FixedClock(new DateTime(2024, 5, 3, 8, 30, 0)));
var lunch = new OpeningHours(new FixedClock(new DateTime(2024, 5, 3, 12, 15, 0)));
Console.WriteLine($"8:30 {early.Status()}");
Console.WriteLine($"12:15 {lunch.Status()}");

interface IClock { DateTime Now { get; } }

record FixedClock(DateTime Now) : IClock;

class OpeningHours
{
    private readonly IClock clock;
    public OpeningHours(IClock clock) => this.clock = clock;
    public string Status() => clock.Now.Hour switch
    {
        >= 9 and < 17 => "Open",
        _ => "Closed",
    };
}

The real program would pass a clock whose Now reads the computer's time, and OpeningHours would never know.