Why should I write (as my collegue says):
import static org.apache.commons.lang.math.NumberUtils.INTEGER_ONE;
if (myIntVariable == INTEGER_ONE) { ... }
instead of:
if (myIntVariable == 1) { ... }
?
I know that the use of constants is recommended but I think the value of NumberUtils.INTEGER_ONE
will never change! So I write 1
.
You should not. The INTEGER_ONE
name is no more meaningful than 1. If however this value has some other meaning (for example, month in the year), then using a constant (like Calendar.FEBRUARY
) will make your code clearer.
I can guess that this constant in Commons Math library was created in Java 1.4 when there were no Integer cache and autoboxing, so it had sense in terms that you may reuse the same Integer
object (not primitive int
) in different places to save memory. So it was added for performance reasons, not for code clarity. Now it's obsolete: even if you need an Integer
object, you can use Integer.valueOf(1)
or implicit autoboxing and get the cached one.