A minor glitch in type-safe enums
Saturday, January 14th, 2006I’m quite fond of the type-safe enum design pattern. However, Wolfgang Hoscheck recently identified a place in XOM where I had introduced a bug as a result of it. Here’s an example:
public class FontStyle {
private int value;
public static FontStyle PLAIN = new FontStyle(1);
public static FontStyle BOLD = new FontStyle(2);
public static FontStyle ITALIC = new FontStyle(3);
public static FontStyle BOLD_ITALIC = new FontStyle(4);
private FontStyle(int value) {
this.value = value;
}
}
The bug shows up in another class that reference the FontStyle
class:
private FontStyle style;
public void setStyle(FontStyle style) {
this.style = style;
}
Do you see the bug? The problem is that there is one thing that can be passed into setStyle
that is not one of the four legal values. Can you guess what it is?
(more…)