Eg.

boolean isCurrent = false;

你怎么命名它的getter和setter?


当前回答

假设你有

boolean active;

Accessors方法

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

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

另请参阅

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

其他回答

对于名为isCurrent的字段,正确的getter / setter命名是setCurrent() / isCurrent()(至少Eclipse是这样认为的),这是非常令人困惑的,可以追溯到主要问题:

首先,您的字段不应该被称为isCurrent。Is是动词,动词不适用于表示对象的状态。使用形容词来代替,你的getter / setter名字会变得更有意义:

private boolean current;

public boolean isCurrent(){
    return current;
}

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

作为一个传达员,你可以:

// setter
public void beCurrent(boolean X) {
    this.isCurrent = X;
}

or

// setter
public void makeCurrent(boolean X) {
    this.isCurrent = X;
}

我不确定这些命名对以英语为母语的人是否有意义。

假设你有

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”并不能阻止糟糕的变量名称,只会产生另一个不必要的规则。

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

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

private boolean current;

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

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