Posted on February 23, 2008 @ 18:08
I’ve got a beef with enums. When I see them, I cringe… which is quite different from my days in C, where I couldn’t live without enums and structs. That’s another story…
“Flyweight: Use sharing to support large numbers of fine-grained objects efficiently” - Design Patterns
Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)
by Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides Read more about this title…
Why do some of us quickly jump to enums? In procedural languages it makes sense. It’s giving a type code a human readable meaning. So instead of having to stare at type code 1, everywhere you can use State.Acknowledgement, which is a lot easier to understand … what does 1 mean again?
But in an OO language, I feel dirty when I see enums. The argument of using it for bitwise operations and the Flags attribute is weak. Create a composite!
Weak… do you really want to use a bitwise & to check if a certain digit is enabled. I don’t. I’m going to use the following 2 tests to squash the enum into a first class component, with some smarts to it.
My current NumberBuilder implementation looks like this (it sucks but it works):
I’m going to start off by creating some Flyweights.
My compiler is telling me that the Add method on my builder currently accepts a parameter of type “Digits”, so I’m going to change the signature to accept a parameter of type IDigit.
Let’s update the NumberBuilder implementation to:
I run the tests and they pass, sweet. But I’m not happy with the current implementation, so I look for other potential refactorings. I decide to forward the digit to append right to the number, the number can take care of how to append the digit, rather then having the builder doing so. The builder now looks like:
And Number looks like:
To wrap this up, Number aggregates digits, the enum got dropped and was replaced by a class. There’s still more refactorings that can occur, but the point is that a full blown component is much easier to extend then an enum…
For more info check out “Replace Type Code with Class” from…
Refactoring: Improving the Design of Existing Code (The Addison-Wesley Object Technology Series)
by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts