Which of the following code is better and why? I have seen many programs written in the first way shown below. Why is it done so?
First Way:
public static final int SIZE = 200000;
public static int[] count;
public static void main(String[] args) {
count = new int[SIZE];
}
Second Way:
public static int[] count;
public static void main(String[] args) {
count = new int[200000];
}
There are two benefits in extracting the constant into a static final field:
Firstly, it has a name - admittedly SIZE
isn't a very good one (size of what? why?) but in other cases it can be very useful to make your intent clear. For example, it's obvious what this means:
private static final long SECONDS_PER_STANDARD_DAY = 24 * 60 * 60;
(although I'd usually use TimeUnit
here). Having the same value within the code - or worse,
the actual numeric value instead of the expression - would be less clear. The above can be
broken down further, of course:
// TODO: Decide between long and int here. Using long means you don't need to be
// as careful when multiplying them together. (Think microseconds etc...)
private static final long HOURS_PER_STANDARD_DAY = 24;
private static final long MINUTES_PER_HOUR = 60;
private static final long SECONDS_PER_MINUTE = 60;
private static final long SECONDS_PER_HOUR = SECONDS_PER_MINUTE * SECONDS_PER_HOUR;
private static final long SECONDS_PER_STANDARD_DAY =
HOURS_PER_STANDARD_DAY * SECONDS_PER_HOURS;
This is precisely the kind of thing I have in Noda Time - I have a public NodaConstants
class with a huge number of these constants, because they're useful both within Noda Time and
also in client code - and the meaning is immediately obvious from the name.
Additionally, it can be used in multiple places, which shows a relationship between those places. If the same number occurs three times in the source code, and you need to change one of them, do you need to change the other? It's hard to tell. If you use a constant, and if every place where the number is needed has carefully decided whether semantically they need the same value, then you can change the value of the constant and all the right places (and only the right places) will see that change.
Some developers take this to an extreme, banning all literals other than zero and one. Personally I view it as a more subtle decision than that. There's a cost to extracting the constant as well as a benefit - the value gets moved away from the code using it. If you're only using the value once, and it's clear from the context why you're using that value, then using the constant obscures the code rather than clarifying it.
I think it's always worth considering whether to extract a constant - but don't go either way in a knee-jerk way.
See more on this question at Stackoverflow