I see 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;
}
When you have define a class and an object of that class,you need this to initialize in setter if the passed argument name and the attribute name of the object are same. Basically this refers to the object through which the call is made.
The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values. You may validate the given value in the setter before actually setting the value.
You may use lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code.
Setters cannot return values. While returning a value from a setter does not produce an error, the returned value is being ignored. Therefore, returning a value from a setter is either unnecessary or a possible error, since the returned value cannot be used.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With