When the Java developers make design decisions, they usually follow ‘best practices’ about code maintainability and what not. So I was surprised to find the following situation in the String class source code (The comments are mine, not theirs obviously).
/* Makes sense, use the appropriate class for this */
public static String valueOf(int i) {
return Integer.toString(i, 10);
}
/* Makes sense, use the appropriate class for this too */
public static String valueOf(float f) {
return Float.toString(f);
}
/* Magic values "true" and "false"? Seriously? */
public static String valueOf(boolean b) {
return b ? "true" : "false";
}
This made me think that for some reason it perhaps might not be defined in Boolean class, or that Boolean references String. Again, I am surprised to find this method is duplicated.
/* Identical code to String */
public static String toString(boolean b) {
return b ? "true" : "false";
}
Now, I understand that it’s highly unlikely the canonical representation of boolean values is likely to change. But how many times have the people who send us (as developers) send us requirements say “Oh, this won’t change – it’s set in stone!” and yet, after a certain amount of time, they come back and say “We need this change, and we need it now!” and hang up before you can tell them they said it would never change.
Is there any particular reason they would do this? I know that sentence makes it sound like it’s murder or something, but still. Am I the only one surprised by this?
"true"and"false"are mandated by the language itself; thus in this case it’s relatively safe to hardcode the string values.Similarly, the language specifies e.g.
nullreferences becomes"null"during string conversion.Generally it’s best not to hardcode constants all over the code base, but when the language guarantees what the constants should be, this becomes less of a problem.
Here’s a snippet from OpenJDK for
AbstractStringBuilder:Note that
StringBuilder extends AbstractStringBuilder.