After I have written a get method in a java class, is it better to use the get method in the same class or the variable itself?
For example:
if(a.getWidth()>this.getWidth())
or:
if(a.getWidth()>this.width)
Also I am confused if i should be using the this.anything so much. It seemed easier to read when comparing objects of the same type to each other.
is it better to use the get method in the same class or the variable itself?
IMHO use the variable. Accessor methods are primarily for other objects to use.
Also I am confused if i should be using the this.anything so much. It seemed easier to read when comparing objects of the same type to each other.
It's not always required for you to explicitly use the this
reference..it's mainly used for readability, like you said.
I think that using the getter methods are better for mantainability. Consider the Null Object pattern which a way to achieve is by making this:
public String getName(){
if (this.name == null){
this.name = "";
}
return this.name;
}
This should save you from checking up a lot of null before operating with the variable.
public boolean isCorrect(){
if(this.name != null && this.name.isEmpty()){
//The null check up is boilerplate code
return false;
}else{
return true;
}
}
I'd rather write this:
public boolean isCorrect(){
if(this.getName().isEmpty()){
//The null check up is boilerplate code
return false;
}else{
return true;
}
}
Of course, this depends if you adopt this pattern.
Also consider that you have
double width;
double height;
public double getWidth(){
return this.width;
}
but at some point you decide to change it for a class but still have the methods so your program doesn't break down.
Dimension dimension;
public double getWidth(){
return this.getDimension().getWidth();
}
// etc...
Finally (as commented by MadProgrammer), when you use inheritance, the methods can be overridden to represent better the intended object.
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