May 19, 2006
The Craftsman: isTooHotForMe!
The wall panel recognized Avery's writing and made sure his code was in a separate sandbox from mine, so that they wouldn't conflict.
"Right," I said, "but that's where the similarity ends. In Java 1.5, an enumeration is actually a class, and each enumerator is a derived class. These classes can have variables:"
public class Taco {
enum Color {red, green, burntumber}
enum Salsa {
mild(10, Color.red),
medium(1000, Color.green),
hot(100000, Color.burntumber);
public final int scovilles;
public final Color color;
Salsa(int scovilles, Color color) {
this.scovilles = scovilles;
this.color = color;
} } }
"That's pretty cool," Jasmine smiled at Jerry. "The enum has a constructor and instance variables!"
Jerry looked at the wall for a second and said, "Yeah, that's pretty useful. This means that a constant can have more than one value. Consider this representation for a Red/Green/Blue color:"
public enum RGB {
red(0xff, 0x00, 0x00),
green(0x00, 0xff, 0x00),
blue(0x00, 0x00, 0xff),
white(0xff,0xff,0xff);
public final int r;
public final int g;
public final int b;
RGB(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
} }
I muscled my way back up to the wall and said, "Right, and this allows you to do interesting things, such as:"
public class Taco {
enum Color {red, green, burntumber}
enum Salsa {
mild(10, Color.red),
medium(1000, Color.green),
hot(100000, Color.burntumber);
public final int scovilles;
public final Color color;
Salsa(int scovilles, Color color) {
this.scovilles = scovilles;
this.color = color;
} }
public static boolean isTooHotForMe(Salsa s) {
return s.scovilles > 30000;
} }
Jasmine jumped in. "That means we can write code that makes decisions about enums without knowing any of the enumerations!"
"Huh?" said Jerry. "What do you mean?"
"Well, just look at what Alphonse wrote!" she urged. "The isTooHotForMe method will work for any enumerator within the Salsa enumeration. Even if we add new enumerators later, the isTooHotForMe method will continue to work unchanged."
"Yes! The Open-Closed Principle!" I blurted.
"And," Avery pointed out, "we can add, change or remove enumerations without affecting the isTooHotForMe method!"
Jerry looked intently at the wall for a few seconds. "That implies a whole new way of thinking about constants and enums," he said. "Sometimes we want to depend on the internal structure instead of knowing what enumerators are there. We could write an isBlue function like this:"
class SomeClass {
public static boolean isBlue(RGB color){
return color.b > 2*(color.r + color.g);
}
}
|
|
||||||||||||||||||||||||||||||
|
|
|
|