Eg.
boolean isCurrent = false;
你怎么命名它的getter和setter?
Eg.
boolean isCurrent = false;
你怎么命名它的getter和setter?
当前回答
作为一个传达员,你可以:
// setter
public void beCurrent(boolean X) {
this.isCurrent = X;
}
or
// setter
public void makeCurrent(boolean X) {
this.isCurrent = X;
}
我不确定这些命名对以英语为母语的人是否有意义。
其他回答
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编程语言的代码约定
它应该像其他getter一样get{varname}。将其更改为“is”并不能阻止糟糕的变量名称,只会产生另一个不必要的规则。
考虑程序生成的代码或反射派生。
这是一种无用的约定,一有机会就应该放弃。
强烈建议使用形容词来命名布尔字段。如果您使用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()