Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: is using a final static int = 1 better than just a normal 1?

Tags:

java

I just saw a class (an big API module), where there is alot of stuff like

readParamString(Object params, int index)

and they have in that class 10 fields

final static int PARAM1 = 1
...
final static int PARAM10 = 10

which are being used with readParam functions

but you can also use a normal int like readParamString(o, 1);

is final static int somehow better than using a normal int ?

like image 955
Omu Avatar asked Jan 15 '10 10:01

Omu


3 Answers

One advantage of declaring a static final constant is to prevent multiple references to the same literal value througout the code, which could potentially lead to unwanted variation; e.g. if a programmer inadvertently changes one literal without changing the others.

In your example, I'd question the value of declaring a constant PARAM1 with the value 1, especially if this is private to the containing class and only referenced once. If however, there was some semantic meaning to the literal value then it might be more useful; e.g.

public static final int LOAD_ACTION = 1;
public static final int SAVE_ACTION = 2;
public static final int DELETE_ACTION = 4;
public static final int MOVE_ACTION = 8;

However, typically an enum would be used instead of this approach.

like image 141
Adamski Avatar answered Nov 15 '22 00:11

Adamski


That's silly.

The reason for extracting numeric constants is to give them a telling name. PARAM1..PARAM10 are not very telling.

like image 22
Thorbjørn Ravn Andersen Avatar answered Nov 15 '22 01:11

Thorbjørn Ravn Andersen


In the example you give, I'd say that having the named values is not better than just using the int directly. The parameter is a count, so the int representation of the parameter is just as descriptive as the named version.

This seems to be kind of like when I occasionally come across C code that has things like

#define ZERO 0
#define ONE 1

There's really not much point. In fact, when I see those names used (instead of when I'm looking at the definitions), I get tempted to jump to the defines to make sure the names aren't lying (It's been a long, long time, but, I've actually come across code that had FALSE defined to 1, -1 or something non-zero, for example, which is really, really bad).


Edit: on second look, it appears that the names might indicate which field in the first parameter that are of interest, in which case the names might make more sense - as long as the names have some meaningful tie to the field rather than just the numeric offset. It's hard to say whether or not that's the case, since you might be paraphrasing the code you're really working with.

like image 41
Michael Burr Avatar answered Nov 15 '22 02:11

Michael Burr