0 day streak
csharp / intermediate
Snippet

Isolating External State with Interface Abstractions

Abstracting external systems like the system clock behind an interface is critical for testing. It allows you to inject a 'mock' provider during unit tests to return a fixed date, ensuring deterministic test results.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
public interface IDateTimeProvider
{
DateTime Now { get; }
}
public class ReportGenerator
{
private readonly IDateTimeProvider _dateTime;
public ReportGenerator(IDateTimeProvider dateTime) => _dateTime = dateTime;
public string GetHeader() => $"Report generated on: {_dateTime.Now}";
}
Breakdown
1
public interface IDateTimeProvider
Defines a contract for retrieving the current time without binding to System.DateTime directly.
2
public ReportGenerator(IDateTimeProvider dateTime)
Uses constructor injection to receive a specific implementation of the provider.