Reputation: 9442
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?
Upvotes: 2
Views: 4956
Reputation: 17617
This seems to be a good use of a constant. If this necessarily needs to be private is another question. Might be helpful to be able to read such a value from the outside (especially since it is not modifiable).
Generally speaking constant private fields especially might make sense if the contents of the constant are still modifiable, which might be highly unwanted. Usually in programming the field reference (where it points to) may no longer be changed when set to constant, which does not mean that the underlying object's properties are also fixed (which is usually NOT the case). This also sort of belongs to the topic of pass-by-value vs pass-by-reference and its implications for copying (deep vs shallow) etc.
Upvotes: 0
Reputation: 14084
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.)
Upvotes: 4
Reputation:
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.
Upvotes: 2
Reputation: 405765
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.)
Upvotes: 6