I often write code which translates entities in the database to domain objects. These entities often have fields which are constrained and translate to enumerations in the domain objects. In some cases, though, the fields can be null.
For example, imagine I have a PrintJob
entity with a Status
field that can be New
, Submitted
, or Completed
and a Result
field that can be Succeeded
, FailedNoPaper
, or FailedNoToner
but it can also be NULL
if the Status
is not Completed
.
On the one hand, I like having a one-to-one mapping of entity field values to domain object enum values, but on the other hand, it somehow feels "better" to always have values for properties with enumeration types.
My question is: is it better to represent the value of the Result
field in my domain object as a nullable value (e.g. MyStatus?
in C# or VB.NET) having essentially no value when the corresponding entity field is NULL
, or should I create a special enum value along with the others, e.g. NoValue
or Undefined
?
Best Answer
If a field value is one of a list of predefined values, your domain will have a real-world value that you can correspond to NULL. All you have to do is look for it. If the Status is not completed its result could be 'NotFinished', 'Unavailable', 'DoesNotExist' or 'Unknown'.
Think about this in a non-code way. If you print something and ask a colleague to bring over the stack of papers from the printer, how would he let you know that there is no printout on the printer? He might say it isn't finished yet, it wasn't available yet, there was nothing on the printer...
As far as enums go, I'm not a big fan of nullable enums. Add a single, default field such as 'Unknown' and you NEVER EVER have to worry about it being NULL. Otherwise, you will spend reams of code in your application to first check for NULL before doing anything sensible... Enums, like booleans, should shy away from being NULL.