r/coding • • Sep 19 '18

Java 11 String API Updates

https://4comprehension.com/java-11-string-api-updates/
38 Upvotes

11 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Sep 19 '18

[deleted]

0

u/TehFrozenYogurt Sep 19 '18

Well yeah I understand that but checking if an Object is null in Java is literally by doing == null. What's the reason for a library to write:

boolean isNull(Object o) { return o == null; }??

Also, again, Strings have isEmpty() already. If we're talking about the CharSequence interface, we already have length().

All I'm saying is that the tasks you provided are trivial to implement or is already implemented. In the OP, they're all examples of non trivial tasks.

5

u/adrianmonk Sep 19 '18 edited Sep 19 '18

They're saying they want a single method that does both checks.

Thus this:

if (s != null && !s.isEmpty()) {
  // do something with s
}

can be replaced with a less error-prone (and slightly easier to type) alternative:

if (!String.isNullOrEmpty(s)) {
  // do something with s
}

And if you use it several times in one .java file, you'd be able to static import the method to make that shorter:

import static java.lang.String.isNullOrEmpty;

// ...

if (!isNullOrEmpty(s1)) {
  // do something with s1
}

if (!isNullOrEmpty(s2)) {
  // do something with s2
}

3

u/NowImAllSet Sep 19 '18

Thanks, this is indeed what I was trying to say. Also want to add the point that it's easier to read, in my opinion. Java is notorious for lack of null safety. Adding a simple method like this would be one (very) small step towards alleviating that.