Dec 11, 2012

Mind the gap: String.isEmpty()

Articles labeled "Mind the gap" are short articles mostly about simple problems that arise from using different API levels of Android. They are more short trivia postings than big teachings about Android development.

I try to write code as readable as possible. That's the reason why I don't want to compare a String to an other empty String object or check its length when I want to know if a String is empty.


In the book "Clean code" by Robert C. Martin you can read Grady Booch saying: "Clean code reads like well-written prose". So I try to use String.isEmpty() for that reason. Internally it may do a length check as well (I stopped my investigation at the native keyword) but when reading the following snippet it is absolutely obvious what I intend to do.


Even though isEmpty() has been introduced in Java 1.6 it hasn't been available in Android until API level 9 (Android 2.3) so I accidentally caused some crashes on earlier versions of Android. Nowadays lint thankfully saves me from doing this error.

So what to do now? I don't know if someone at Google felt the same but there is a class in the Android framework that solves that problem: TextUtils. This class also has a lot of other helpful methods like join() to join an array of elements to a String using a delimiter or getReverse() to reverse a String (Take that interview question!).

In addition to that the TextUtils class has a method isEmpty() that is available since API level 1.


Phew! By the way: Internally isEmpty() checks if the length of the String is 0 (and does a null check).