Eg.

boolean isCurrent = false;

你怎么命名它的getter和setter?


当前回答

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

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;

其他回答

private boolean current;

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

public boolean hasCurrent(){
    return this.current;
}

我相信会是:

void setCurrent(boolean current)
boolean isCurrent()

数据类型Boolean的setter/getter方法和类中的Boolean(对于pojo/实体)之间有一个可标记的点。

对于Boolean和Boolean, setter方法都应该是setXXX(),而getter方法分别是getXXX()和isXXX()

例子:

(a)如果属性定义为布尔值

private Boolean active;

setter/getter方法

public Boolean getCheck() {   // getXXX()
    return check;
}

public void setCheck(Boolean check) {
    this.check = check;
}

(b)如果属性定义为布尔值

private boolean check;

setter/getter方法

   public boolean isCheck() {   // isXXX()
        return check;
    }
    public void setCheck(boolean check) {
        this.check = check;
    }

强烈建议使用形容词来命名布尔字段。如果您使用IntelliJ生成getter和setter,您将发现对于布尔字段current和isCurrent, getter都是isCurrent()。

我们可以看一下IntelliJ社区源代码,它的测试数据显示,无论你的布尔字段名是否以is开头,getter的名字都是以is开头。

class Getter {
  boolean foo;
  boolean isBar;
  boolean hasBaz;

  @java.lang.SuppressWarnings("all")
  public boolean isFoo() {
      return this.foo;
  }

  @java.lang.SuppressWarnings("all")
  public boolean isBar() {
      return this.isBar;
  }

  @java.lang.SuppressWarnings("all")
  public boolean isHasBaz() {
      return this.hasBaz;
  }
}

当你想调用getter时,当你的布尔字段名以is开头时,你会很困惑。此外,当您的同事想要获得您定义的布尔字段的值时,他们将只知道getter的名称而不是字段的名称。在这种情况下,前缀is是不必要的。

这里是另一个例子,当我从数据库检索数据来实例化一个Employee对象时,isRetired的值总是false。因为Java没有找到合适的setter,布尔字段的值总是默认值,比如false,这是不期望的。

class Employee{
    private int age;
    private boolean isRetired;

    ...
    public boolean setRetired(boolean isRetired){
        this.isRetired = isRetired;
    }
}
Setter: public void setCurrent(boolean val)
Getter: public boolean getCurrent()

对于布尔值,也可以使用

public boolean isCurrent()