I’m in the process of designing an API, part of which involves writing POCOs to a database.
In C#, we have the DateTime
structure. The “default” value for this (DateTime.MinValue
) is 01/01/0001.
Part of the API serializes POCOs to the database. If a date field is optional, it should really be nullable (in C# syntax, this would be defined as DateTime?
). What I’d like to avoid, is programmers falling in to the trap of writing DateTime.MinValue
to the database at all. It’s a valid date, for sure – but smells of something. So I am debating implementing a BestPracticeException
class that would be thrown in circumstances such as this.
If the user of the API really needs to deal with that date, they probably also need to deal with dates prior to that and need an entirely different structure (e.g comparing how many months have occurred between 500 BC and today).
Do you think preventing writing 01/01/0001 to the database, on the whole, is a good thing to do? One might argue that you need to differentiate between being no date entered, and the user entering nothing. My answer to that would be it is the function of a more broader auditing process that would pick that up, rather than attempting to ascertain intent from a field being null, or not null.
4
Violating a best practice is not an exceptional condition. If you want to declare that 01/01/0001 is an invalid value, then throw an exception for that, specifically.
Looking forward to the day when my IDE throws an InvalidBraceStyleException
.
2
A date of 01/01/0001
would usually indicate a bug. Someone probably has used a default-initialized variable.
Your intention basically is to have a runtime assert to guard against a specific class of bugs. That’s a valid thing to do. In fact it is done all the time.
Consider having this validation as a layer between the client and the storage API. Like this:
var date = GetDate();
Validate(date);
Store(date);
Instead of:
void Store(DateTime dateTime) {
Validate(dateTime);
StoreImpl(dateTime);
}
Let callers choose whether they want this validation or not. By convention, have most or even all callers perform the validation. This keeps the validation out of the storage system.