Thursday, June 29, 2023

Horror Code: Boolean Parsing Fest

 This article was originally posted on JRoller on September 21, 2015

A small gem I found the other day:

String value = ...
boolean booleanValue = Boolean.valueOf(value.toLowerCase()).booleanValue();

A lot of useless stuff:

  • toLowerCase is useless because the Boolean class is using equalsIgnoreCase.
  • booleanValue is unnecessary because of automatic unboxing.
  • Boolean.valueOf creates a useless temporary Boolean object.

Why does it seem so hard to parse a boolean?

boolean booleanValue = Boolean.parseBoolean(value);

And this works even if value is null.

No comments:

Post a Comment