Cleaner Java: Apache Commons

While strolling though some Java code today, I ran across a few common patterns that are easily improvable.

Oftentimes we check if something is null, or empty:

if (queryMap == null || queryMap.isEmpty()) {…}

Apache Commons provides a number of utility classes that provide just this sort of check:

if ( MapUtils.isEmpty(queryMap) ) {…}

MapUtils is part of Collections4 which can help with a number of common use-cases around Java Collections.

MapUtils can also help with this code:

String code = (String) queryMap.get(CODE);

String name = (String) queryMap.get(NAME);

if (code == null && name == null) {…}

Here the values in the queryMap may not exist, hence the null check later. Hidden here is that if the value in the queryMap happens to not be a String (this is a Map<String, Object>), then we’ll get a class cast exception at runtime. Since this queryMap happens to be from user input, this edge-case is easily reachable with the result being a HTTP 500 Internal Server error being returned.

MapUtils to the rescue:

String code = MapUtils.getString(queryMap, CODE, null);

String name = MapUtils.getString(queryMap, NAME, null);

if (null == code && null == name)

This takes care of the ugly class cast exception, and explicitly defines a default “null” should the key not be found in the Map. Better.

Apache Common’s Lang3 also has similar utility methods for Strings (and other things) in StringUtils.

So this:

if (myString == null || myString.isEmpty()) {…}

Becomes:

if (StringUtils.isBlank(myString)) {…}

Shorter and easier to read.

Of course there are other utility libraries out there. These are just a few very common ones that are simple to include in a Java Service, that help with writing more maintainable and easier to read code.