Is StringUtils.EMPTY recommended?

后端 未结 11 1922
情深已故
情深已故 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:00

    I use StringUtils.EMPTY, for hiding the literal and also to express that return StringUtils.EMPTY was fully expected and there should return an empty string, "" can lead to the assumption that "" can be easily changed into something else and that this was maybe only a mistake. I think the EMPTY is more expressive.

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

    If your class doesn't use anything else from commons then it'd be a pity to have this dependency just for this magic value.

    The designer of the StringUtils makes heavy use of this constant, and it's the right thing to do, but that doesn't mean that you should use it as well.

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

    I find StringUtils.EMPTY useful in some cases for legibility. Particularly with:

    1. Ternary operator eg.

      item.getId() != null ? item.getId() : StringUtils.EMPTY;
      
    2. Returning empty String from a method, to confirm that yes I really wanted to do that.

    Also by using a constant, a reference to StringUtils.EMPTY is created. Otherwise if you try to instantiate the String literal "" each time the JVM will have to check if it exists in the String pool already (which it likely will, so no extra instance creation overhead). Surely using StringUtils.EMPTY avoids the need to check the String pool?

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

    No, because I have more to write. And an empty String is plattform independent empty (in Java).

    File.separator is better than "/" or "\".

    But do as you like. You can't get an typo like return " ";

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

    Yes, it makes sense. It might not be the only way to go but I can see very little in the way of saying this "doesn't make sense".

    In my opinion:

    • It stands out more than "".
    • It explains that you meant empty, and that blank will likely not do.
    • It will still require changing everywhere if you don't define your own variable and use it in multiple places.
    • If you don't allow free string literals in code then this helps.
    0 讨论(0)
  • 2020-12-08 02:11

    I'm amazed at how many people are happy to blindly assume that "" is indeed an empty string, and doesn't (accidentally?) contain any of Unicode's wonderful invisible and non-spacing characters. For the love of all that is good and decent, use EMPTY whenever you can.

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