Is making an empty string constant worth it?

I much prefer seeing EMPTY_STRING.

It makes it english. "".equals 'reads' differently than EMPTY_STRING.equals.


Ironically the whole point of constants is to make them easily changeable. So unless your co-worker plans to redefine EMPTY_STRING to be something other than an empty string - which would be a really stupid thing to do - casting a genuine fixed construct such as "" to a constant is a bad thing.

As Dan Dyer says, its like defining the constant ONE to be 1: it is completely pointless and would be utterly confusing - potentially risky - if someone redefined it.


String literals are interned by default, so no matter how many times you refer to "" in code, there will only be one empty String object. I don't see any benefit in declaring EMPTY_STRING. Otherwise, you might as well declare ONE, TWO, THREE, FOUR, etc. for integer literals.

Of course, if you want to change the value of EMPTY_STRING later, it's handy to have it in one place ;)


Why on earth would you want a global variable in Java? James Gosling really tried to get rid of them; don't bring them back, please.

Either

0 == possiblyEmptyString.length()

or

possiblyEmptyString.isEmpty() // Java 6 only

are just as clear.

Tags:

Java

String