Thursday, June 29, 2023

Horror Code: Empty Integer

 This article was originally published on JRoller on July 20, 2012

I just found this interesting piece of code:

  Integer oldGroupId = ...
  Integer groupId = (oldGroupId.toString().trim().equals(GUIConstants.EMPTY_STRING)) ? NumberConstants.ZERO_INTEGER : oldGroupId;

At first, I was not quite sure why he used the Integer class. Either he would expect the value to be possibly null, and a nice NPE would result of the following code. Or he wanted to use the toString method, ignoring that a static version exists in the Integer class.

And then, he trims the String, maybe not trusting that those guys developing Java would return a clean String. Better be on the safe side.

But the nicest touch of all, is that all of this is for testing if the trimmed String is empty. One must now take some minutes to consider what possible value of an integer can give back an empty String. When one finished pondering, one will just remove all this jibber-jabber and replace it with a simpler int assignment.

No comments:

Post a Comment