Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a boolean property name prefixed by "is" still a valid Java Bean?

I just noticed something I didn't know.

  private boolean isCertified;

  public boolean isCertified() {
    return isCertified;
  }

  public void setCertified(boolean certified) {
    isCertified = certified;
  }

The following getters and setters have been generated by Intellij. By the way, Lombok generate the same kind of getters and setters.

I would have expected something like:

  private boolean isCertified;

  public boolean isIsCertified() {
    return isCertified;
  }

  public void setIsCertified(boolean certified) {
    isCertified = certified;
  }

That's why I usually don't prefix my boolean attributes with ìs, despites the fact I think the property name becomes more readable.

I normally write something like:

  private boolean certified;

  public boolean isCertified() {
    return certified;
  }

  public void setCertified(boolean certified) {
    certified = certified;
  }

So I wonder:

  • Having a property named isXXX and a getter being isXXX instead of isIsXXX: is it a valid Java Bean definition?

  • Are there any other hidden Java Bean corner cases like that, that I may want to know to improve the code readability?

Thanks

like image 1000
Sebastien Lorber Avatar asked Jun 12 '13 13:06

Sebastien Lorber


2 Answers

AFAIK, the naming pattern of fields is not part of the JavaBeans specification.

The JavaBeans Specification specifies (among others) the "properties" concept.

The properties of a class are identified by the methods (named after a certain pattern) of a class.

The fields are irrelevant. In fact, there doesn't even have to be a field for a property.

That said, it's still a good practice to name the fields after the property names. The chance is greater that tools which need to access the fields as well (e.g. refactoring support in IDEs) will handle the fields correctly.

Having a property named isXXX and a getter being isXXX instead of isIsXXX: is it a valid Java Bean definition?

No, a getter for a property isXXX requires isIsXXX() (for boolean) or getIsXXX().

But again it's the other way around.

If you have a method:

boolean isXyz()

then you have a readable property xyz.

If you have a method

boolean isIsXyz()

then you have a readable property isXyz.

For more information have a look at the Introspector class, the tutorial or the JavaBeans Specification:

http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html

http://www.oracle.com/technetwork/java/javase/tech/index-jsp-138795.html

like image 68
Puce Avatar answered Nov 15 '22 14:11

Puce


private boolean certified;

public boolean isCertified() {
    return certified;
}

public void setCertified(boolean certified) {
    this.certified = certified;
}

It's ok. More info about variables names you can look on oracle.docs

like image 37
Petr Shypila Avatar answered Nov 15 '22 13:11

Petr Shypila