Null evil vs nil punning

Interesting timing to see a reply here this morning as this subject cropped up for me late last night in a discussion on the Java Moose forums about refactoring. The (Java) code being refactored had a condition in it to either produce null or a String as the result of a parsing function. In this case, they’d used String.indexOf() which returns -1 for no match, and had a condition to specifically translate that to null.

I decided to show the Clojure equivalent where both clojure.string/index-of and re-find return nil if there’s no match and so you no longer need to special case for the null return.

I used (second (re-find ..)) with a group in the regex to replace the entire function they were asking about refactoring, eliminating all the statements in their function, leaving just one expression without if – part of the refactoring goal in the thread was to eliminate the conditional (in this case it was specifically the ternary operator in a return statement. Using (and (str/index-of ..) (subs .. (str/index-of ..) ..)) would also work because of nil-punning.

Dropping Clojure into a Java thread wasn’t welcomed by everyone but someone did say that if Clojure addresses the Billion Dollar Mistake, it was definitely worth a look!

8 Likes