Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For a boolean field, what is the naming convention for its getter/setter?

People also ask

How do you name a setter and getter?

The getter should start with 'get', followed by the member name, with its first letter capitalized. Also the latest conventions I heard of, say that we should avoid multiple capital letters one after another. For example getHTMLtooltip is wrong. it should be getHtmlTooltip instead.

Should Boolean variables start with is?

[Mandatory] Do not add 'is' as prefix while defining Boolean variable, since it may cause a serialization exception in some Java frameworks.


Suppose you have

boolean active;

Accessors method would be

public boolean isActive(){return this.active;}

public void setActive(boolean active){this.active = active;}

See Also

  • Java Programming/Java Beans
  • Code Conventions for the Java Programming Language

http://geosoft.no/development/javastyle.html#Specific

  1. is prefix should be used for boolean variables and methods.

    isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for boolean methods and variables used by Sun for the Java core packages. Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.

Setter methods for boolean variables must have set prefix as in:

void setFound(boolean isFound);

There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

boolean hasLicense(); 
boolean canEvaluate(); 
boolean shouldAbort = false;

For a field named isCurrent, the correct getter / setter naming is setCurrent() / isCurrent() (at least that's what Eclipse thinks), which is highly confusing and can be traced back to the main problem:

Your field should not be called isCurrent in the first place. Is is a verb and verbs are inappropriate to represent an Object's state. Use an adjective instead, and suddenly your getter / setter names will make more sense:

private boolean current;

public boolean isCurrent(){
    return current;
}

public void setCurrent(final boolean current){
    this.current = current;
}

I believe it would be:

void setCurrent(boolean current)
boolean isCurrent()