For a Boolean Field, What Is the Naming Convention for Its Getter/Setter

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

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

What should be the name of getter method for a boolean variable starting with `is`

First of all, in Java we usually don't tag member variables with an "m" prefix.

The usual (Java Bean) convention is the variable be named

boolean mobilePresent

and the getter

public boolean isMobilePresent

Alternatively, a has-prefix can be used

public boolean hasConfiguredMobileConnections;

Where is the JavaBeans naming convention defined?

Answer: Here and here.

Java boolean setter with has prefix according to naming convention

The problem in your case is not only finding an appropriate name for the setter. It is also that your getter does not follow the conventions!

The specification and the tutorial are very clear on this:

  • The setter for a property should be prefixed with set
  • The getter for a non-boolean property should be prefixed with get
  • The getter for a boolean property should be prefixed with is

And it is important to follow these conventions, because otherwise, many automatic (reflection-based) tools will no longer work as expected (e.g. Introspectors).


Grammar aside, there are several options for solving this. In a comment, it was suggested to call the property isParent, although then, strictly speaking, the accessor would have to be called isIsParent...

So I'd suggest to simply call the property something like havingChildren or owningChildren, and offer the corresponding accessor methods like isHavingChildren/setHavingChildren, or
isOwningChildren/setOwningChildren, respectively.

What is getter/setter naming convention in java for a boolean such as canProduce?

It looks like the standard approach for booleans is the is/set approach as eclipse autogenerate code like that so I finally opted for an approach like this in order to have a more readable methods:

boolean ableToProduce;
public boolean isAbleToProduce() {
return ableToProduce;
}
public void setAbleToProduce(boolean ableToProduce) {
this.ableToProduce = ableToProduce;
}


Related Topics



Leave a reply



Submit