问题
Which of the following declarations conforms to Java's naming conventions?
private boolean writerIsEnabled;
// with methods like
public boolean getWriterIsEnabled()
public void setWriterIsEnabled()
OR
private boolean writerEnabled;
// with methods like
public boolean getWriterEnabled()
public void setWriterEnabled()
I personally find the first name "writerIsEnabled" to be more readable, especially when you use it in an if statement like this -
if(writerIsEnabled)
{
//...
}
回答1:
As far as I know, it's this way:
private boolean writerEnabled;
// with methods like
public boolean isWriterEnabled();
public void setWriterEnabled(boolean enabled);
Either when the type is boolean
or Boolean
, the difference is that the Getter starts with is
instead of get
.
Personally I prefer the isWriterEnabled
approach. Technologies like, for example, JSF respect that standard when accessing properties. The EL expressions are acknowledged with is
and get
.
回答2:
If this is in a writer class, you'd probably want to remove the Writer from your variable.
I would typically not use Is
in my field names, but would in the methods.
Something like this:
private boolean writerEnabled;
public boolean isWriterEnabled();
public void setWriterEnabled(boolean enabled);
Although this is my personal naming convention, you should probably talk with any others who you're working with, to see what they would use.
回答3:
private boolean writerEnabled;
public boolean isWriterEnabled()
public void setWriterEnabled()
回答4:
For the getter and setter methods, I believe the convention is public boolean isWriterEnabled()
and public boolean isReaderEnabled()
.
As for the variable, it should be private boolean writerEnabled
.
来源:https://stackoverflow.com/questions/11941485/java-naming-convention-for-boolean-variable-names-writerenabled-vs-writerisenab