Is StringUtils.EMPTY recommended?

后端 未结 11 1923
情深已故
情深已故 2020-12-08 01:46

Do you use StringUtils.EMPTY instead of \"\"?

I mean either as a return value or if you set a the value of a String variable. I don\'t mean

相关标签:
11条回答
  • 2020-12-08 02:15

    Of course not. Do you really think "" is not clear enough ?

    Constants have essentially 3 use cases:

    1. Document the meaning of a value (with constant name + javadoc)
    2. Synchronize clients on a common value.
    3. Provide a shortcut to a special value to avoid some init costs

    None apply here.

    0 讨论(0)
  • 2020-12-08 02:15

    I will add my two cents here because I don't see anybody talking about String interning and Class initialization:

    • All String literals in Java sources are interned, making any "" and StringUtils.EMPTY the same object
    • Using StringUtils.EMPTY can initialize StringUtils class, as it accesses its static member EMPTY only if it is not declared final (the JLS is specific on that point). However, org.apache.commons.lang3.StringUtils.EMPTY is final, so it won't initialize the class.

    See a related answer on String interning and on Class initialization, referring to the JLS 12.4.1.

    0 讨论(0)
  • 2020-12-08 02:15

    I don't really like to use it, as return ""; is shorter than return StringUtils.EMPTY.

    However, one false advantage of using it is that if you type return " "; instead of return "";, you may encounter different behavior (regarding if you test correctly an empty String or not).

    0 讨论(0)
  • 2020-12-08 02:19

    Honestly, I don't see much use of either. If you want to compare egainst an empty string, just use StringUtils.isNotEmpty(..)

    0 讨论(0)
  • 2020-12-08 02:20

    No, just use "".

    The literal "" is clear as crystal. There is no misunderstanding as to what was meant. I wouldn't know why you would need a class constant for that. I can only assume that this constant is used throughout the package containing StringUtils instead of "". That doesn't mean you should use it, though.

    If there's a rock on the sidewalk, you don't have to throw it.

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