C#: dependency injection makes code testable
Dependency injection means a class receives the objects it depends on instead of creating them. If Greeter called DateTime.Now itself, its output would change with the time of day, and a test could not control it. Depending on an interface lets callers supply any implementation.
C#
using System;
interface IClock {
int Hour { get; }
}
class SystemClock : IClock {
public int Hour { get { return DateTime.Now.Hour; } }
}
class FixedClock : IClock {
public FixedClock(int hour) {
Hour = hour;
}
public int Hour { get; }
}
class Greeter {
private readonly IClock clock;
public Greeter(IClock clock) {
this.clock = clock;
}
public string Greet() {
return clock.Hour < 12 ? "Good morning" : "Good afternoon";
}
}
class Program {
static void Main() {
Console.WriteLine(new Greeter(new FixedClock(9)).Greet());
Console.WriteLine(new Greeter(new FixedClock(15)).Greet());
}
}