Java Tip #3: Use Apache Commons StringUtils for String checks

The next tip in my series of Java Tips deals with the usage of Java frameworks. Some people still have a certain hatred against Java frameworks because many of them have been not easy to deal with in in their past. Nevertheless, while those have either disappeared or evolved in a more usable shape, there have always been some frameworks which were rock-solid and widely accepted as simple and extremely useful. One of those is the Lang package in the library collection of the Apache Commons. In my opinion this one is a must-have for almost every Java project or application. Use it. Period.


Advice

Use Commons StringUtils for checking Strings content for null, emptiness or blankness.

Code-Example

Before

if(str != null && !str.equals("")) { ... }
if(str != null && !str.trim().equals("")) { ... }
if("".equals(str)) { ... }
if(str == null || "".equals(str.trim())) { ... }

After

if(StringUtils.isNotEmpty(str)) { ... }
if(StringUtils.isNotBlank(str)) { ... }
if(StringUtils.isEmpty(str)) { ... }
if(StringUtils.isBlank(str)) { ... }

Benefit

Huge readability gain. Safety gain, as StringUtils methods are null-safe. By using the provided utility methods from StringUtils the intent of a condition is much easier and faster to recognize. Furthermore, since all methods of StringUtils are able to correctly process null Strings, there is no danger of an unexpected NullPointerException anymore because of a forgotten null-check.

Remarks

None.

|

Similar entries