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;
    }

假设你有

boolean active;

Accessors方法

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

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

另请参阅

Java编程/Java Beans Java编程语言的代码约定

它应该像其他getter一样get{varname}。将其更改为“is”并不能阻止糟糕的变量名称,只会产生另一个不必要的规则。

考虑程序生成的代码或反射派生。

这是一种无用的约定,一有机会就应该放弃。