Is making an empty string constant worth it?

前端 未结 18 694
無奈伤痛
無奈伤痛 2021-01-01 10:11

I have a co-worker that swears by

//in a singleton \"Constants\" class
public static final String EMPTY_STRING = \"\";

in a constants class

相关标签:
18条回答
  • 2021-01-01 10:31

    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.*

    0 讨论(0)
  • 2021-01-01 10:32

    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 ;)

    0 讨论(0)
  • 2021-01-01 10:35

    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.

    0 讨论(0)
  • 2021-01-01 10:35

    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:

    • Check the various other cases, including being null safe, and (more importantly)
    • Conveys what you are trying to test, rather than how to test it.
    0 讨论(0)
  • 2021-01-01 10:36

    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.

    0 讨论(0)
  • 2021-01-01 10:36

    Or simply just have it as string.IsNullOrEmpty(otherString)

    0 讨论(0)
提交回复
热议问题