Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How far should best practices like avoiding magic number should go? [closed]

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...?

like image 230
Omnipresent Avatar asked Dec 12 '22 12:12

Omnipresent


1 Answers

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

  • ...it increases readability,
  • ...the value may change (and is used in multiple places), or
  • ...it serves as documentation

A related side note: As always with coding standards / conventions: very few (if any) rules should be followed strictly.

like image 70
aioobe Avatar answered Dec 21 '22 22:12

aioobe