112

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 for comparison, because there we use StringUtils.isEmpty()

nabster
  • 1,561
  • 2
  • 20
  • 32
keuleJ
  • 3,418
  • 4
  • 30
  • 51

12 Answers12

139

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.

David Pierre
  • 9,459
  • 4
  • 40
  • 32
  • 48
    I still see one one minor and rare use case for `StringUtils.EMPTY`. It makes it clear that the use of the empty String is intended, and not some sort of laziness ("Oh, this requires a String, let's pass `""`"). If someone hits this piece of code, he'll think twice before making changes. Also, if `StringUtils.EMPTY` were defined as your own variable, like `MyClass.EMPTY`, making changes to "that representation of emptiness" would require changing one line of code. You could, for example, change it to `""` instead of the empty String `""`. But, I think this is going a bit too far. – Timmos Jan 22 '14 at 09:09
  • 5
    Finally I have some sane argument to forward zealots to, instead of thinking on my own every time. Thanks. – Alex Dec 15 '15 at 16:52
  • 4
    How does EMPTY lack meaning? EMPTY satisfies both 1 and 2 in your list. The experienced developers are severely underestimating the potential for junior developers to mess up something as simple as using "". – Andrew T Finnell Jul 27 '18 at 14:40
  • 8
    @AndrewTFinnell the name `EMPTY` doesn’t bear any meaning which the empty string itself doesn’t already have. Most notably, it doesn’t document *why* you decided to use an empty string at that particular case. It’s not different to naming a constant `ONE` and pretending there was a point in using that constant instead of the value. – Holger Sep 11 '18 at 13:09
  • 11
    Down votes just because, no, I actually don't think "" is clear enough :( Is it blank? Is it empty? Is there a space in there I can't see because my font size is small? Was it intended to be empty? Are there any strange "invisible" chars? – Dan Rayson Sep 11 '18 at 16:13
  • 3
    yeah "" is not clear at all. its hard to read and easy to miss. – Mubashar Jun 03 '19 at 04:05
  • 2
    for everyone that said `""` is easy to miss, do you not have other string constants? how do you sleep at night knowing there could be an extra space at the end of any of them? – Pita Aug 17 '20 at 18:39
78

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.

Carlos López Marí
  • 1,432
  • 3
  • 18
  • 45
Christopher Klewes
  • 11,181
  • 18
  • 74
  • 102
  • 45
    As per others who have suggested this: do you also use ZERO for 0 and ONE for 1? – Jon Skeet Nov 04 '10 at 10:33
  • 9
    I wouldn't compare the special 'empty' case to the use of the integer literal. – Christopher Klewes Nov 04 '10 at 12:30
  • 18
    I find `StringUtils.EMPTY` _less_ expressive than `""`. – bacar Sep 26 '13 at 14:06
  • 1
    @JonSkeet Much respect to you. I do feel like you are incorrect here. While you and I may never encounter this, there is a case to be made to not use the literal "" as it provides no syntax checking if a developer messes it up. And yes, I have seen junior developers mess up simple things like "". I don't buy into the idea of ever changing EMPTY to mean something else than "". I like the idea of EMPTY only for the fact the compiler is able to understand it's meaning. – Andrew T Finnell Jul 27 '18 at 14:39
  • @AndrewTFinnell: "Incorrect" is an odd term for what must surely be subjective. No, I don't expect EMPTY to ever change meaning, but I - like bacar - find `""` to be more expressive than using `StringUtils.EMPTY`, and what you've said hasn't changed my mind on that. I can just about believe that developers have incorrectly written an empty string literal *very, very occasionally* - but I'll take the clarity of the string literal over the once-in-a-million (and easily found in testing, hopefully...) bug, personally. – Jon Skeet Jul 27 '18 at 18:05
  • @JonSkeet Quite right. It is subjective. I would never use StringUtils.EMPTY either as you can static import to EMPTY. I do appreciate the succinctness of “”. I do not believe the fact a compiler can catch EMPTY being wrong versus “” to be subjective though. – Andrew T Finnell Jul 27 '18 at 18:07
  • @Andrew: No, but the relative importance of that Vs what I consider to be the better readbility of "" is subjective. (I'm not overly worried about the possibility I've never seen in the wild. I've seen lack of bracds cause bugs, I expect seen all kinds of things - but never that. So I maintain it's at least vanishingly rare, at least with the colleagues I've worked with.) – Jon Skeet Jul 27 '18 at 22:04
  • One thing that I don't see mentioned (and I realise this is really quite pedantic at this point) is that "" (double speech marks) could in theory be mistaken for '"' (single quotes with a speech mark inside it) as well at a glance. – John Darvill Aug 05 '22 at 10:45
32

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.

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
  • 12
    "If there's a rock on the sidewalk, you don't have to throw it." Tell that to my 6 year old son. – roel Sep 28 '17 at 09:28
25

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.

j__m
  • 9,392
  • 1
  • 32
  • 56
  • 4
    I'm curious - have you ever seen this happen in code? If so, was it accidental or on purpose? It would seem difficult to do accidentally, and if on purpose, well I could just as easily create my own StringUtils class with a non-empty EMPTY constant, and refer to that. – Ian Robertson Sep 29 '17 at 19:30
  • 7
    @IanRobertson Yes, I have seen this happen. Quite often actually. People cut and paste from websites all the time and from one Code Set to another Code Set. There are also companies which still use Clear Case which uses an archaic code set, which is then blindly translated into the windows ISO set, and is then translated into UTF-8 if you move to Git. I have spent countless hours fixing code set problems. Including this one. – Andrew T Finnell Jul 27 '18 at 14:33
  • 4
    @AndrewTFinnell I can certainly see how in general, that could cause issues. But how often have you specifically seen a non-empty empty-looking String constant? – Ian Robertson Jul 28 '18 at 01:25
  • This is what Unit Tests exist for. They must eliminate any such typos / anomalies at early stage helping to avoid any unexpected behavior. – RAM237 Aug 10 '21 at 14:50
24

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.

Matthieu
  • 2,736
  • 4
  • 57
  • 87
  • 1
    “only if it is not declared final”, so since this field is declared final, accessing it can **not** cause the initialization of the `StringUtils` class. – Holger Nov 06 '19 at 10:28
  • @Holger that was a general statement but indeed, I edited with a link to the javadoc showing it is final (and thus won't initialize the class). – Matthieu Nov 06 '19 at 13:34
12

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

syntagma
  • 23,346
  • 16
  • 78
  • 134
Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273
  • 14
    Have you ever observed this actually being a problem (using " " accidentally where you meant "")? Personally I find the literal more readable, and it's never caused me any problems. – Jon Skeet Nov 04 '10 at 10:06
  • 2
    @Jon No, indeed, but I tried to find an advantage of using it ;) – Romain Linsolas Nov 04 '10 at 10:21
  • 1
    There is no equal time rule. If there is no advantage, then there is no advantage. – Erick Robertson Nov 04 '10 at 12:45
  • 1
    I don't like `""` also, I hate to type the same literal string more than one time, even once only sometimes. I'd rather declare constants in **Constants.java**, but not repeat them everywhere in source code. – xenophōn Jan 30 '18 at 03:24
  • 2
    I **THINK** `return "";` is ugly, I **PREFER** to use return `StringUtil.EMPTY` (declared in my own class **StringUtil**, NOT Apache's **StringUtils**). – xenophōn Jan 30 '18 at 03:27
6

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.

cherouvim
  • 31,725
  • 15
  • 104
  • 153
  • I meant it's acceptable since the author chose to go this way (avoid any use of "magic values"). It should be private though. – cherouvim Nov 04 '10 at 10:15
  • The author uses 0 frequently in the code. Would it have been better for them to define a constant int ZERO = 0 as well? If not, what's the difference? – Jon Skeet Nov 04 '10 at 10:18
  • 6
    It depends on the context. If this was an FCKEditorStringUtils, their EMPTY would be "

    &nbsp

    " and I'd rather see EMPTY reused instead of replicating this magic value everywhere in the class. So, by EMPTY they probably mean EMPTY_CONTENT and not EMPTY_STRING (so your ZERO example is a bit unfair). Wouldn't you re-use an ERROR_VISA_INVALID=0 constant?
    – cherouvim Nov 04 '10 at 12:45
3

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?

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
Tom
  • 91
  • 5
  • 4
    Your argument with the multiple lookups doesn't hold. In chapter 13.4.9 of the Java Language Specification 3.0, it is mentioned that the `StringUtils.EMPTY` constant is resolved at compile-time. – Roland Illig Jan 02 '14 at 07:46
  • 4
    Existence in the string pool is checked at compile time and class loading time, not at runtime ever y time you execute such a statement, – user207421 Sep 25 '16 at 11:07
  • 1
    Since `StringUtil.EMPTY` is a compile-time constant, a reference to it gets compiled to exactly the same bytecode as using `""` directly. Further, I don’t see why the ternary operator should make any difference. It’s an expression like any other. Any reason to use or not to use a named constant applies to the ternary operator as well. – Holger May 18 '18 at 07:12
2

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

Matthieu
  • 2,736
  • 4
  • 57
  • 87
Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79
  • 8
    I quite don't understand why most programmers are so afraid of writing "too much". By writing StringUtils.EMPTY you'll achieve self commenting code, one that is easier to read. And according to Steve McConnell (or some study that he quoted in Code Complete 2.0) code is read 7 times more than it is written. – Paweł Dyda Nov 04 '10 at 11:46
  • 1
    You are particular right, BUT: "".equals(someString) is as easy to read as StringUtils.EMPTY.equals(someString) – Christian Kuetbach Nov 04 '10 at 11:50
  • StringUtils.EMPTY.equals(someString) will result in a Syntax error if you write it incorrectly. "".equals(someString) will not. This is the only reason one needs to use EMPTY. – Andrew T Finnell Jul 27 '18 at 14:36
  • 1
    @AndrewTFinnell that’s why sane programmers write `someString.isEmpty()` instead. – Holger Nov 06 '19 at 10:31
1

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 2
    `StringUtils.isNotEmpty(..)` also does a nullcheck so it's not exactly the same as comparing with an empty string. – cherouvim Nov 04 '10 at 10:08
  • and how will you campare `null` ? as a 2nd argument of `equals`, but the result will be the same - `false` – Bozho Nov 04 '10 at 10:20
  • `isNotEmpty` is the opposite of `"".equals(…)`, hence, the fact that it will treat `null` like the empty string *is* different to comparing with an empty string, `"".equals("")`→`true`, `"".equals(null)`→`false`, `StringUtils.isNotEmpty("")`→`false`, `StringUtils.isNotEmpty(null)`→`false`. If you just want to know whether a string is empty, use `string.isEmpty()`, which has the right behavior of returning `true` iff it is an empty string and throwing a `NullPointerException` if the string is `null`… – Holger May 18 '18 at 07:08
0

I am recommending to use this constant as one of the building stones of a robust code, to lower the risk of accidently have nonvisible characters sneak in when assigning an empty string to a variable.

If you have people from all around the world in your team and maybe some of them not so experienced, then it might be a good idea to insist on using this constant in the code.

There are lots of different languages around and people are using their own local alphabet settings on their computers. Sometimes they just forget to switch back when coding and after they switch and delete with backspace, then text editor can leave some junk inside of "". Using StringUtils.EMPTY just eliminate that risk.

However, this does not have any significant impact on the performance of the code, nor on the code readability. Also it does not resolve some fundamental problem you might experience, so it is totally up to your good judgement weather you will use this constant or not.

Saša
  • 4,416
  • 1
  • 27
  • 41
-1

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.
Oron
  • 931
  • 7
  • 9
  • 2
    `It will still require changing everywhere if you don't define your own variable and use it in multiple places.` you are gonna change an empty string to a different empty string? – Pita Aug 17 '20 at 18:35
  • @Pita Sorry, that was poor phrasing. I meant to say that if you use this inline instead of "" you still don't get the same benefits as defining your own constant and reusing in multiple places. It's not an argument for StringUtils.EMPTY, it's an explanation that you don't get much even if it 'makes sense'. Personally, I would create a constant with a descriptive name and then either assign this. I've seen a few cases where a developer intended a single space and ended up with an empty string, which doesn't happen with this form. – Oron Aug 18 '20 at 21:55