Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct syntax for "is" variable getter/setters in a POJO class?

Tags:

java

pojo

If a class contains a variable named "blah", then the standard getter/setter syntax is obviously getBlah() and setBlah(). But if I have a POJO class with a variable named isBlah, would I use:

public type getIsBlah() {
  return isBlah;
}

public setIsBlah(type isBlah) {
  this.isBlah = isBlah;
}

Or would it be this?

public type isBlah() {
  return isBlah;
}

public setBlah(type blah) {
  this.isBlah = blah;
}

The first seems to conform more strictly to the POJO conventions, but the second type is what IntelliJ generates if I ask it to make a class' getter/setters (and hey, IntelliJ has never let me down yet :] ). So which is the preferred syntax?

like image 204
Nik Reiman Avatar asked Jul 13 '09 08:07

Nik Reiman


People also ask

Can POJO have getters and setters?

A typical POJO class consists of private fields with its getter and setter methods or accessors (Which is not mandatory). You can have fields and accessors with any access level in a POJO.

What is getter and setter method in Java?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

Can POJO have getters?

The definition of POJO doesn't mandate getter/setter.

How do you use setters and getters in two different classes?

To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B . You can do this e.g. by passing it as a parameter to a method of B , or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter .


1 Answers

One reason for using properties is to decouple the API from the implementation. In other words, you shouldn't feel bound by what your private variable is called. That shouldn't inform the naming beyond trying to keep it readable to code maintainers.

I would say that if "type" is boolean in this case, then the second form is correct. If it's not boolean, you should use getXXX - but I probably wouldn't use getIsXXX. To me, "is" has a very strong correspondence with Boolean properties, and using it in other contexts would not only break the JavaBeans conventions (which could affect other tools) but would be misleading IMO.

like image 140
Jon Skeet Avatar answered Oct 21 '22 12:10

Jon Skeet