In near future we might be enforced by a rule by which we can not have any hard coded numbers in our java source code. All the hard coded numbers must be declared as final
variables.
Even though this sounds great in theory it is really hard/tedious to implement in code, especially legacy code. Should it really be considered "best practice" to declare numbers in following code snippets as final
variables?
//creating excel
cellnum = 0;
//Declaring variables.
Object[] result = new Object[2];
//adding dash to ssn
return ssn.substring(1, 3)+"-"+ssn.substring(3, 5)+"-"+ssn.substring(5, 9);
Above are just some of the examples I could think of, but in these (and others) where would you as a developer say enough is enough?
I wanted to make this question a community wiki but couldn't see how...?
Definitely no. Literal constants have their places, especially low constants such as 0
, 1
, 2
, ...
I don't think anyone would think
double[] pair = new double[PAIR_COUNT];
makes more sense than
double[] pair = new double[2];
I'd say use final variables if
A related side note: As always with coding standards / conventions: very few (if any) rules should be followed strictly.
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