Sending enums between my Java code and a database or client app, I often end up reading and writing the enum values as strings. toString()
is called implicitly when concatenating strings. Overriding toString() on some enums meant that that sometimes I could just
"<input type='checkbox' value='" + MY_CONST1 + "'>"
and sometimes I had to remember to call
"<input type='checkbox' value='" + MY_CONST1.name() + "'>"
which led to errors, so I don't do that anymore. Actually, I don't override any methods on Enum because if you throw them around to enough client code, you'll eventually break someone's expectations.
Make your own new method name, like public String text()
or toEnglish()
or whatever.
Here is a little helper function that could save you some typing if you have lots of enums like the above:
public static String ucFirstLowerRest(String s) {
if ( (s == null) || (s.length() < 1) ) {
return s;
} else if (s.length() == 1) {
return s.toUpperCase();
} else {
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
}
It's always easy to call .toUpperCase() or .toLowerCase() but getting back mixed-case can be tricky. Consider the color, "bleu de France." France is always capitalized, so you may want to add a textLower() method to your enum if you run into that. When you use this text at the beginning of a sentence, vs. the middle of a sentence, vs. in a title, you can see how a single toString()
method is going to fall short. And that doesn't even touch characters that are illegal in Java identifiers, or that are a pain to type because they aren't represented on standard keyboards, or characters that don't have case (Kanji, etc.).
enum Color {
BLEU_DE_FRANCE {
@Override public String textTc() { return "Bleu De France"; }
@Override public String textLc() { return "bleu de France"; }
}
CAFE_NOIR {
@Override public String textTc() { return "Café Noir"; }
}
RED,
YELLOW,
GREEN;
// The text in title case
private final String textTc;
private Color() {
textTc = ucFirstLowerRest(this.toString());
}
// Title case
public String textTc() { return textTc; }
// For the middle of a sentence
public String textLc() { return textTc().toLowerCase(); }
// For the start of a sentence
public String textUcFirst() {
String lc = textLc();
return lc.substring(0, 1).toUpperCase() + lc.substring(1);
}
}
It is not so difficult to use these properly:
IllegalStateException(color1.textUcFirst() + " clashes horribly with " +
color2.textLc() + "!")
Hopefully that also demonstrates why using mixed-case enum values will disappoint you as well. One last reason to keep with all-caps with underscores enum constants is that doing so follows the Principle of Least Astonishment. People expect it, so if you do something different, you are always going to have to be explaining yourself, or dealing with people misusing your code.