views:

938

answers:

3

Is it right to use a private constant in the following situation:

Say I have a game with a lives variable and a startingLives variable. At the start of the game I set the lives variable to equal the startingLives variable. This is how I would normally do it:

private var lives:int = 0;
private var startingLives:int = 3;

private function startGame():void
{
   lives = startingLives;
}

(example code is ActionScript btw)

My question is - should this really be:

private var lives:int = 0;
private const STARTING_LIVES:int = 3;

private function startGame():void
{
  lives = STARTING_LIVES;
}

StartingLives seems unlikely to change at runtime, so should I use a const, and change back to a variable if it turns out not to be constant?

UPDATE: The consensus seems to be that this is a good use of a constant, but what about amdfan's suggestion that you may want to load the value in from a config file?

+4  A: 

Put it in a constant named DEFAULT_STARTING_LIVES, but also have a variable named startingLives. For now, set startingLives = DEFAULT_STARTING_LIVES. Later, you can set startingLives based on a value from a configuration file. If the file has not been created or is not found, you have a back up.

(thanks to Plinth for the expansion on my original answer.)

amdfan
That's a good point!
Iain
For loading from a file, you'd want a var - but you STILL want the constant - it will be your default setting (ie, startingLives = DEFAULT_STARTING_LIVES;)
plinth
You should use the code tag to keep your formatting. Thanks for the helpful answers!
Iain
+4  A: 

Yeah, this is a good use of a const. As a general rule of thumb, any "variable" whose value won't change at runtime should be made a constant. This enables the compiler to optimize those values by putting them in a separate (ROM) area of memory. (NOTE: That's not a guarantee that your compiler will optimize, it just makes it possible.)

Bill the Lizard
Making it const also lets anyone reading the code know exactly what your intent is for that value.
carson
What about amdfan's point that you might want to make the app data-driven and load this value from a config file?
Iain
Then he would change it back when he decides it needs to go in a config file.
Bill the Lizard
+1  A: 

I think a private constant is appropriate where it has no use outside of that context, and would result in clutter if made public.

Certainly using a constant in your case is better than a magic number - especially if you need to use it in more than one place.

Jon B