Saturday, December 15, 2007 #

Dragging enums into the OO world

   1: public enum Weekday {
   2:     Monday,
   3:     Tuesday,
   4:     Wednesday,
   5:     Thursday,
   6:     Friday,
   7:     Saturday,
   8:     Sunday
   9: };

 

What's wrong with this code?

This looks like C# but actually you could already do this in C in the 1970's. In those days the ability to define your own types was a novel idea but in today's object-oriented languages we expect a bit more, like extensibility or the possibility to inherit from types.

What if we want to extend our Weekday-type with a method to check for weekends? Or a 'Next' and 'Previous' method? Usually these will end up as static methods in some Utility class. Smelly! I want to be able to do this:

   1: if( Weekday.Saturday.IsWeekend() ) {
   2:    ...
   3: }

Let's try again. This time with class :-)

   1: public class Weekday {
   2:     public static Weekday Monday = new Weekday();
   3:     public static Weekday Tuesday = new Weekday();
   4:     public static Weekday Wednesday = new Weekday();
   5:     public static Weekday Thursday = new Weekday();
   6:     public static Weekday Friday = new Weekday();
   7:     public static Weekday Saturday = new Weekday();
   8:     public static Weekday Sunday = new Weekday();
   9: }

Now why exactly is this better? It looks like a lot more work.

Maybe because you can extend it like this?

   1: public class Weekday {
   2:     public static Weekday Monday = new Weekday();
   3:     public static Weekday Tuesday = new Weekday();
   4:     public static Weekday Wednesday = new Weekday();
   5:     public static Weekday Thursday = new Weekday();
   6:     public static Weekday Friday = new Weekday();
   7:     public static Weekday Saturday = new Weekday();
   8:     public static Weekday Sunday = new Weekday();
   9:  
  10:     public bool IsWeekend() {
  11:         // ...
  12:     }
  13:  
  14:     public Weekday Next() {
  15:         // ...
  16:     }
  17:  
  18:     public Weekday Prev() {
  19:         // ...
  20:     }
  21: }

Looks familiar? Take a look at the System.Drawing.Color class.

posted @ Saturday, December 15, 2007 3:59 PM | Feedback (4)

Copyright © Mendelt Siebenga

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski