Creating enum which sucks

April 22nd, 2009

We 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:

C#:
  1. enum Mood
  2. {
  3.     Unknown = -1,
  4.     Awesome,
  5.     Cool,
  6.     Bad,
  7.     Awful
  8. }

It does not look bad at the first look, yet another enum.

Another programmer created a list:

C#:
  1. List<mood> availableMoods = new List<mood>();
  2. availableMoods.Add(Mood.Awful);
  3. 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:

C#:
  1. Mood found = availableMoods.Find(
  2.     delegate(Mood f)
  3.     {
  4.         return f == Mood.Awesome || f == Mood.Cool;
  5.     }
  6. );

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.

  1. Create different enum where the default element will be "Unknown = 0"
  2. Use FindIndex method of List(T) class so we will be able to handle the situation of not found element
  3. 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?

Designed by SirMike © All rights reserved

Valid XHTML 1.0! Valid CSS!

Powered by Rootnode