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;

其他回答

对于名为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;
}

强烈建议使用形容词来命名布尔字段。如果您使用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 beCurrent(boolean X) {
    this.isCurrent = X;
}

or

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

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

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

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

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

假设你有

boolean active;

Accessors方法

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

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

另请参阅

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