There has been talk of Enums in general violating Clean Code-principles, so I’m looking for people’s favorite Enum anti-patterns and alternative solutions for these.
For example I’ve seen code like this:
switch(enumValue) {
case myEnum.Value1:
// ...
break;
case myEnum.Value2:
// ...
break;
}
It’s one step better than switch-statements with magic strings, but this probably could have been solved better with a factory, a container or other pattern.
Or even old-school code like this:
if(enumValue == myEnum.Value1) {
// ...
} else if (enumValue == myEnum.Value2) {
// ...
}
What other anti-patterns and better implementations have you experienced with enums?
I think Enums are quite useful. I’ve written a few extensions for Enum that have added even more value to its use
First, there’s the Description extension method
This will allow me to define en enum like this:
And get the label by doing this:
var myLabel = rectangle.widthunit.Description()(eliminating any need for aswitchstatement).This will btw return “px” if
rectangle.widthunit = MeasurementUnitType.Pixelsor it will return “px,em” ifrectangle.widthunit = MeasurementUnitType.Pixels | MeasurementUnitType.Em.Then, there is a
Which will let me traverse any enum with int based values and return the int values themselves.
I find these to be very useful in an allready useful concept.