Creating enum which sucks
April 22nd, 2009We create many enumerations in our programs. But sometimes we can make a mistake that drives somebody else mad.
Let's suppose that the first programmer created an enum like this:
-
enum Mood
-
{
-
Unknown = -1,
-
Awesome,
-
Cool,
-
Bad,
-
Awful
-
}
It does not look bad at the first look, yet another enum.
Another programmer created a list:
-
availableMoods.Add(Mood.Awful);
-
availableMoods.Add(Mood.Bad);
Then he would like to find there a first mood type which is a part of "good mood" group and pass the result to another layer of an application. He wrote the code:
-
Mood found = availableMoods.Find(
-
delegate(Mood f)
-
{
-
return f == Mood.Awesome || f == Mood.Cool;
-
}
-
);
Now he realized that it cannot work because Find method of a List(T) class returns default(T) when a list does not contain desired item. In this case he would get Mood.Awesome because it is the default value of the enum. I do not need to add that the Mood.Awesome is not even the part of the list.
We can solve this problem by several different approaches.
- Create different enum where the default element will be "Unknown = 0"
- Use FindIndex method of List(T) class so we will be able to handle the situation of not found element
- I believe that other approaches could work as well
The question to discuss - which programmer made a mistake? The first one who created "unfortunate" enum or the second one who used wrong structure / wrong searching method?
