Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java convention for using get methods inside other methods of the same class?

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.

like image 559
Doug B Avatar asked Feb 17 '23 18:02

Doug B


2 Answers

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.

like image 122
mre Avatar answered Mar 09 '23 00:03

mre


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.

like image 29
Roger Avatar answered Mar 09 '23 01:03

Roger