J-Yen
J-Yen

Reputation: 687

Required attribute for primitive types makes no sense

In my use case I need a required boolean property, for example:

public class Todo 
{ 
    [Required] 
    public bool IsDone {get; set; } 
}

I experienced a bug in my Entity Framework project due to a missing property mapping (value was not set) of a boolean property. As a result I always stored the default boolean value ‘false’ while it’s actually not filled in. When not filled in I expect to throw a validation exception but because it’s a primitive type the validation attribute makes no sense as it always have a default value which is sufficient to pass. I don’t want to have a default value and the validation attribute should throw an exception when the value is not set.

A solution what I came up with is to use nullable booleans with the required attribute. In case the property is not set the required attribute will throw an exception which is great. On the other side it's pretty weird to have a required nullable boolean because you known it's always filled in (due to the required attribute) and it makes the business logic about this property less readable (IsDone.HasValue? IsDone.Value : false; /Should not be possible because it's required/).

Any other solutions possible?

Upvotes: 3

Views: 952

Answers (1)

Andrei Dragotoniu
Andrei Dragotoniu

Reputation: 6335

There are a number of options here. What you want is a triple state mechanism : not set, true, false

Nullable bool does provide that, however the main question is if this is clear to consumers.

A second option would be to create a triple state enum and use that instead.

  • Is it clearer? Maybe
  • Is it extensible? Yes, but do we really require more then 3 states?

Between the two, I would go with a nullable bool myself. In the end it's a pick your poison kind of situation.

Upvotes: 2

Related Questions