Tuesday, September 18, 2007

Replacing Enum Constructs with Classes

In my previous post on this topic, I promised an exposition of the design pattern that I proposed. To briefly restate the motivation, rather when this pattern is indicated, when you have a set of relatively static values, typically something that might become an enumeration in your application, consider using this pattern. It frees you from having to map values to enumeration members when persisting, serializing, integrating, etc. Instead the class can implicitly be casted to the appropriate value. Please see the previous post for a clearer explanation.


The basic mechanism to implement our pattern is to create static accessors (public static fields) on our "category" class for each "category". Imagine we have three types of parts:

  • Widgets
  • Whoozits
  • Whatzits

Each of which corresponds to a code in our enteprise systems:
  • G
  • O
  • A



Some of enterprise web services take this code as an argument, and our data access layer certainly will require specifying the part type. Our design pattern is indicated here. Here's the code.



As you can see, we expose all of the currently known part types as static properties of the PartTypes class. In practice, this looks much like using an enum to consumers of our PartTypes class without the attendant complications we reviewed in my previous post on the topic.


This is an easy pattern to apply and can great simplify using these categories in code. A common extension to the pattern that I use in my applications is to expose a Predicate<T> for each of the categories. I will leave that as an exercise for the reader.

No comments: