Differences

This shows you the differences between two versions of the page.

Link to this comparison view

it:ad:patterns:enums_start_with_undefined_strategy [2019/03/24 12:02] (current)
Line 1: Line 1:
 +# IT:​AD:​Patterns:​Enums Start with Undefined Strategy #
  
 +
 +
 +<callout type="​Navigation"​ class="​small">​
 +* [[../​|(UP)]]
 +{{indexmenu>​.#​2|nsort tsort}}
 +
 +
 +</​callout>​
 +
 +
 +<panel title="​Summary">​
 +
 +
 +
 +</​panel>​
 +
 +
 +## Process ##
 +
 +Consider ​
 +
 +<sxh>
 +public enum Gender{
 +  Male =1,
 +  Female =2
 +}
 +</​sxh>​
 +
 +Much as you don't want to admit it...zero'​s are a common source of bugs. So if your code somehow ends up setting a property to:
 +
 +<sxh>
 +  person.Gender= ​ (Gender)0
 +</​sxh>​
 +
 +You'll be surprised to know that it won't complain, even if 0 is not a member of the enum list.
 +
 +The only way that you can Validate such a scenario is by doing something like the following.
 +
 +<sxh>
 +public static void Validate(this Person person){
 +   if ( ((int)person.Gender) == 0){throw ....}
 +}
 +</​sxh>​
 +
 +which of course nobody will do (as they'​ll be thinking about using the enum, not the unitituive int).
 +
 +
 +So just account for the use of a zero getting in there somehow. Put it at the beginning of the enum:
 +
 +
 +<sxh>
 +public enum Gender{
 +  Undefined=0
 +  Male =1,
 +  Female =2
 +}
 +</​sxh>​
 +
 +Now you can test for it. 
 +
 +<sxh>
 +public static void Validate(this Person person){
 +   if (person.Gender == Gender.Undefined){throw ....}
 +}
 +</​sxh>​
 +
 +
 +While you're at it, you might as well consider whether there is such a case as Unknown. In which case, give it a value of 1:
 +
 +<sxh>
 +public enum Gender{
 +  Undefined=0,​
 +  Unknown=1,
 +  Male =2,
 +  Female =3,
 +}
 +</​sxh>​
 +
 +
 +Now it's clearer.