Using identical String literals instead of a final variable?-Collection of common programming errors

The advantage is not in performance, but in maintainability and reliability.

Let me take a real example I came across just recently. A programmer created a function that took a String parameter that identified the type of a transaction. Then in the program he did string compares against this type. Like:

if (type.equals("stock"))
{ ... do whatever ... }

Then he called this function, passing it the value “Stock”.

Do you notice the difference in capitalization? Neither did the original programmer. It proved to be a fairly subtle bug to figure out, because even looking at both listings, the difference in capitalization didn’t strike me.

If instead he had declared a final static, say

final static String stock="stock";

Then the first time he tried to pass in “Stock” instead of “stock”, he would have gotten a compile-time error.

Better still in this example would have been to make an enum, but let’s assume he actually had to write the string to an output file or something so it had to be a string.

Using final statics gives at least x advantages:

(1) If you mis-spell it, you get a compile-time error, rather than a possibly-subtle run-time error.

(2) A static can assign a meaingful name to a value. Which is more comprehensible:

if (employeeType.equals("R")) ...

or

if (employeeType.equals(EmployeeType.RETIRED)) ...

(3) When there are multiple related values, you can put a group of final statics together at the top of the program, thus informing future readers what all the possible values are. I’ve had plenty of times when I’ve seen a function compare a value against two or three literals. And that leaves me wondering: Are there other possible values, or is this it? (Better still is often to have an enum, but that’s another story.)