Effective-Dated Rules: Never Default to UtcNow
If your rules change over time, each one needs a date it came into force. The default value of that date is where this goes wrong.
The problem
public sealed class Rule
{
// Looks harmless. Is not.
public DateTime EffectiveFrom { get; } = DateTime.UtcNow;
}The rule is now in force from the moment the object happened to be constructed. Which is: whenever the app last started, or whenever the seeder ran.
Resolve a rule for something dated earlier and you match nothing at all. Import two years of historical records and every one of them resolves to "no applicable rule".
Make it an input
public sealed class Rule
{
// Beginning of time by default: the rule has always applied unless
// the caller says otherwise.
public DateTime EffectiveFrom { get; }
public Rule(string key, DateTime? effectiveFrom = null)
{
Key = key;
EffectiveFrom = effectiveFrom ?? DateTime.MinValue;
}
}Rules that encode long-standing policy get the default and apply to all of history. Rules that genuinely start on a date get that date, explicitly.
Why it matters
The failure is invisible in every test you're likely to write, because tests create a rule and immediately use it — with UtcNow a millisecond in the past, it matches.
It only shows up with historical data: a backlog import, a reopened old record, a report over last year. By then the code has been "working" for months.
When in doubt, ask what the rule describes. If it encodes policy that predates your system, it cannot have come into force the day you deployed.