Eg.

boolean isCurrent = false;

你怎么命名它的getter和setter?


当前回答

private boolean current;

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

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

其他回答

假设你有

boolean active;

Accessors方法

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

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

另请参阅

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

也许是时候开始修改这个答案了?就我个人而言,我会投票给setActive()和unsetActive()(替代方案可以是setUnActive(), notActive(), disable()等,取决于上下文),因为“setActive”意味着你在任何时候都激活它,而你没有。说"setActive"有点违反直觉,但实际上删除了活动状态。

另一个问题是,你不能以CQRS的方式专门监听一个setActiveEvent,你需要监听一个'setActiveEvent',并确定该监听器内部是否实际上被设置为活动的。当然,也可以在调用setActive()时确定调用哪个事件,但这违背了关注点分离原则。

关于这一点,Martin Fowler的FlagArgument文章是一篇不错的文章:http://martinfowler.com/bliki/FlagArgument.html

然而,我有PHP的背景,看到这种趋势被越来越多地采用。不知道这与Java开发有多大关系。

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;

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

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

or

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

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

Setter: public void setCurrent(boolean val)
Getter: public boolean getCurrent()

对于布尔值,也可以使用

public boolean isCurrent()