I'm working on an ASP.NET MVC app, designing the domain models, using (testing) the new EF Code First feature.
I have an Activity entity that may or may not have a Deadline, what is the best way to approach it?
1 property:
public DateTime? Deadline {get; set;}
and check vs null before using
or
2 properties:
public DateTime Deadline {get; set;}
public bool HasDeadline {get; set;}
At first I thought of the first option, but then I started thinking that maybe the second option would be better regarding the DB...
Is there any best practice regarding this?
Although using nullable reference types can introduce its own set of problems, I still think it's beneficial because it helps you find potential bugs and allows you to better express your intent in the code. For new projects, I would recommend you enable the feature and do your best to write code without warnings.
For example, you can assign any of the following three values to a bool? variable: true , false , or null . An underlying value type T cannot be a nullable value type itself.
This feature improves user satisfaction by reducing errors and app crashes. Null safety ensures that all runtime null-dereference problems are shown at compile-time. It helps you avoid many problems during development, rather than waiting until runtime to identify null errors.
A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value. The Nullable types are instances of System.
I'd go with the first option. After all, it's exactly an encapsulated form of the second.
The encapsulation makes it clear that you've only got one logical value (or lack thereof). In the second form you can treat the properties as if they were entirely independent, which they're logically not.
In terms of the database, I'd expect the first form to be just as easy too... presuambly you'll have a nullable DATETIME field in the database, won't you? It should map directly.
How about a combination of both just for the sake of making your code more readable?
public DateTime? Dealine{get; set;}
public bool HasDeadline
{
get
{
return (Deadline != null);
}
}
Its easy to read and does exactly the same thing that the consumer would have to do anyway. Besides...
if(HasDeadline)
doStuff();
is easier to read than
if(Dealine != null)
doStuff();
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With