Question

I have a big file of constants. Is this a valid way to initialize them?

private static int i = 0;

public static final int ITEM_GOLD = i++;
public static final int ITEM_ZINC = i++;
public static final int ITEM_TIN = i++;
....

ITEM_GOLD should equal 0, ITEM_ZINC should equal 1, ITEM_TIN should equal 2 and so on.

Was it helpful?

Solution

Yes, this should work. However, I would recommend to use the enum class instead. If the number really has some semantic (not just an arbitrary discriminator of a constant) then this is ok, otherwise enum is better (can be used in switch, the code is more readable, etc..)

If you don't want to introduce a new file, you may want to declare the enum in the surrounding class:

public TheClass {
   ...
   enum Item {
     GOLD, ZYNC, TIN
   }
   ...
}

OTHER TIPS

Although not a straight answer, it is the right one in my mind. try this and see, much faster to discover that way
As for what values is a good approach, use enums or constants, makes it much more readable and maintainable.
Dynamic values might change in the future and give u unexpected results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top