My question is related to Is making an empty string constant worth it?.
I know constants should have meaningful names, but is there any benefit in extracting primitive values like ints in Java in a Constants file like:
public final static int ZERO = 0;
to use as general-purpose constants and keep reusing it like Constants.ZERO
in your code-base or better use the literal value of 0?
What about general-purpose booleans? i.e.
public static final boolean TRUE = true;
public static final boolean FALSE = false;
For the constants you are defining, there's no reason for them because there is no extra meaning. The literals 0
, true
, and false
already have their meaning.
Constants would be worth creating if there is some extra meaning to attach to those values, such as:
public static final int SUCCESS = 0;
public static final boolean DEBUG = true;
There is meaning behind these values, and it's possible that they may change:
public static final int SUCCESS = 1;
public static final boolean DEBUG = false;
which would make it easier to change the values than changing lots of literals in the program.
If the values have meaning beyond their literal values, and if they could change, then creating constants is worth the effort.
If it makes your program easier to understand or maintain, yes. Otherwise, no.
The HotSpot VM probably complies your code to the same machine code either way.
And by the way, Boolean.TRUE and Boolean.FALSE already exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With