I s开发者_开发技巧ee no real difference between the following two methods of creating a setter, but was wondering if I am just naive. Is one more desirable than the other?
public void fooSetter(String bar)
{
_bar = bar;
}
public void fooSetter(String bar)
{
this._bar = bar;
}
There is no semantic difference in this case because there is no ambiguity. If, on the other hand, your instance field was also called bar
then this
would be required to disambiguate:
public void fooSetter(String bar)
{
this.bar = bar;
}
You do not need "this" since there is no ambiguity. ("bar" and "_bar" are different. now if your field was called "bar" as well, you'd need it)
The different styles are mostly caused by what a programmer did before Java, what coding standards are present in the company, etc.
The desired style is to use:
public class A {
private Type property;
public Type getProperty(){
return this.property;
}
public void setProperty(Type property){
this.property = property;
}
}
This is kind of the best-practice style and complies to the JavaBeans standard.
When you're using setters in Java, this
can be helpful to escape the current variable scope. If you instead had
private String bar = "";
public void fooSetter(String bar){
this.bar = bar
}
That would correctly set the class variable instead of that function variable
Is one more desirable than the other?
Depends on the scope you want to use-
public class myClass{
private int number=5;
private void setNumbers(float number){
number=1; // refers to local variable (float)
this.number=2; // refers to class variable (int)
}
}
I like to use "this.variable" whenever I refer to a class variable, you'll note that Eclipse will also highlight class variables in blue where local variables stay black which can be helpful.
I prefer the second way, just because it makes it clear to the reader and it's consistent since it's needed when the the parameter and field are both named the same (when it is necessary so as to differentiate what is being set). There is no functional difference between the two in this example, though.
this
is explicit and for that reason is preferred by many. In some cases the difference is significant, however. e.g. a member variable and local variable of the same name.
public void fooSetter(String bar)
{
String _bar = fancyfilter(bar);
this._bar = _bar;
}
A somewhat contrived example, but you get the idea.
your setters should be
setFoo(String foo)
and
public String getFoo()
to conform to javabean conventions.
If the reference name in the setter (foo) is the same as the property on the class, then you should use 'this' to be explicit.
As has been said, it is disambiguous, but I prefer without using this as well.
I would go with something like this which also prevents ambiguity by giving names more explicit to the variables purpose.
public void setBar(String newBar)
{
bar = newBar;
}
This would be my first choice, the second would be to use the this, I wouldn't consider the underscores.
精彩评论