Java: Why no true constants?

I find it odd that Java–a language intended to facilitate and encourage the development of elegant programs–never finalized (no pun intended) a way of expressing true constants. The closest you can get is “final” variables, that can only be initialized once, i.e.:

private static final int MSG_ERROR = 1;

But, they fall short, as they can’t be used in place of a constant expression, such as a “case” label in a “switch” construct; i.e., this will fail:

switch(msgLevel) {
case this.MSG_ERROR:
// do something
break;
}

because javac doesn’t consider a “final” variable to be a constant expression. You’d have to do:

switch(msgLevel) {
case 1:
// do something
break;
}

Which renders the case label’s purpose less than intuitive. Sure, we could use a comment after each case label, but that’s rather hack-ish, in my opinion: one of the most widely accepted best practices for writing clear code is to avoid the use of “magic” numbers (numeric constants that aren’t self-explanatory). In the case of Java, the language itself forces us–in certain cases–to use them. For a statically-typed language–even one with built-in garbage collection and automatic memory management–this seems a rather shameful trade-off. Apparently, Java reserved a keyword for constants early on, but it was shelved somewhere around 2005.

Why, Java? Why?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s