I have a co-worker that swears by
//in a singleton \"Constants\" class
public static final String EMPTY_STRING = \"\";
in a constants class
We just do the following for situations like this:
public class StaticUtils
{
public static boolean empty(CharSequence cs)
{
return cs == null || cs.length() == 0;
}
public static boolean has(CharSequence cs)
{
return !empty(cs);
}
}
Then just import static StaticUtils.*
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 ;)
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.
As a tangent to the question, I generally recommend using a utility function when what you're really checking for is "no useful value" rather than, specifically, the empty string. In general, I tend to use:
import org.apache.commons.lang.StringUtils;
// Check if a String is whitespace, empty ("") or null.
StringUtils.isBlank(mystr);
// Check if a String is empty ("") or null.
StringUtils.isEmpty(mystr);
The concept being that the above two:
I'm with your coworker. While the empty string is hard to mistype, you can accidentally put a space in there and it may be difficult to notice when scanning the code. More to the point it is a good practice to do this with all of your string constants that get used in more than one place -- although, I tend to do this at the class level rather than as global constants.
FWIW, C# has a static property string.Empty for just this purpose and I find that it improves the readability of the code immensely.
Or simply just have it as string.IsNullOrEmpty(otherString)