Question

For example, to store whether sound is on, I have a boolean originally named "isSoundOn":

private boolean isSoundOn=true;

however, the default value of boolean is false, but I want my application to turn on the sound at start. My question is, should I change the name of isSoundOn into isMute, so that it becomes "false" correctly by default?

Or in general, should I keep a boolean be false by default, even if I may need to reconsider the name of boolean?

Was it helpful?

Solution

No, you absolutely should not choose variable names to conform to your language's default values.

The point of variable names is to make reading code easier for the maintainer. Default values are a detail of the language specification (or sometimes even of the implementation) and may or may not match with your intent in using a flag variable. Therefore it's much, much better to choose the variable name to be as clear as possible for the reader, and use explicit initialization if this is necessary to get the desired initial value.

(By the way, IMO there is no reason to use initialization if the well-defined default value does match your program semantics. Expressions like private boolean active = false; look uncomfortably as if the author didn't know about the language specification and make me wonder what else they don't know.)

OTHER TIPS

Alternative approach would be to have an enum (or based on your programming language a type with only two possible values, but with more descriptive names then true/false)

public enum SoundState
{
    On = 0,  // 'On' by default
    Off = 1
}

Then your code will looks more straightforward about it's intention.

public class Setting
{
    public SoundState Sound { get; set; }
}

var settings = new Setting();

if (settings.Sound == SoundState.On)
{
    // do something
}
Licensed under: CC-BY-SA with attribution
scroll top