Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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.

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