Sunday, August 26, 2012

Cleaner code with Apache Commons

It seems I can no longer write any piece of code without including the Apache Commons libraries.
They just contain everything that the ancient architects of the Java language forgot to include in the java.* APIs; Commons save huge amounts of coding debugging time, by capturing ever repeating patterns, allowing effective reuse which results helps with clean code.

Pattern 1 - Strings comparison

consider the (Apache) common(s) pattern of checking whether two Strings are equal, while any of them is a potential null.
Naively you might try:
[php gutter = "false" lang_name = "Java"]if (s1!=null && s1.equals(s2)) {...}[/php]

But there's a bug coming your way - what if both Strings are null?
[php gutter = "false" lang_name = "Java"]if (s1==s2 || (s1!=null && s1.equals(s2))) {...}[/php]
And we result in verbose ugly, detail oriented, code when all we wanted to know was if two Strings are equal.

With the Apache commons Lang lib, you're exempt from dogging bugs, handling nulls, and reading blurred code, with this intentional piece of code:

[php gutter = "false" lang_name = "Java"]if(StringUtils.equals(s1, s2)) {...}[/php]

Embedding such calls throughout your code seriously cuts down on LOC. Hurray!

Are you using Commons, or you have some other secret weapon down you sleeve?

No comments:

Post a Comment