4

In java for a comparison in an if statement, I wrote

if (x == 1)

and got a comment in code review to use NumberUtils.INTEGER_ONE instead of 1. I was wondering what benefit does it actually add to the code.

Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70
  • Possible duplicate of [Auto Boxing vs static numbers](https://stackoverflow.com/questions/6896317/auto-boxing-vs-static-numbers) – Daniel Eisenreich Jul 14 '17 at 06:43
  • Is `x` a primitive type or an Integer Object? Because if it's the latter, then at least that would prevent autoboxing. Other than that I don't see any major advantages. Maybe your marker doesn't like 'magic numbers' – Dana Jul 14 '17 at 06:46
  • As NumberUtils is in an external jar, unless you are using it already then the benefit of code readability would be next to nothing – Scary Wombat Jul 14 '17 at 06:47
  • It kind of depends what `x` is. It also kind of depends on what `NumberUtils.INTEGER_ONE` is. While `NumberUtils.INTEGER_ONE` is well-specified doing something like that more generically is often a bad idea. I've seen code which have symbolic constants named similarly but with completely wrong value what you would expect from the name (like if `INTEGER_ONE` was the floating-point value `2.0`). – Some programmer dude Jul 14 '17 at 06:48

1 Answers1

5

NumberUtils.INTEGER_ONE comes probably from commons-lang.

In commons-lang, it is defined as :

public static final Integer INTEGER_ONE = new Integer(1);

In commons-lang3, it is defined as :

public static final Integer INTEGER_ONE = Integer.valueOf(1);

The first version doesn't use the internal integer cache (as didn't exist yet) while the second version takes advantage of it.

Now, whatever the version you are using, it doesn't really matter for your question as you compare integer values and you don't assign or create integer value (case where the cache could make more sense).


Suppose you are using it in this way :

if (x == NumberUtils.INTEGER_ONE)
  • If x is a primitive, it is not very efficient as it will produce an unboxing operation to convert NumberUtils.INTEGER_ONE to a 1 int primitive.

  • If x is an object, it is not a good idea either as Integer objects should be compared with equals() or intValue().

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • It is defined as `public static final Integer INTEGER_ONE = Integer.valueOf(1);`. See [this](https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/math/NumberUtils.java#L43). –  Jul 14 '17 at 07:41
  • @saka It depends on the version. In the lang3 version yes and in the lang2 version, no. It doesn't change the problem but I will edit to be clearer. – davidxxx Jul 14 '17 at 08:16