Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any benefit to using getters/setters inside a class for its own fields? [duplicate]

Tags:

java

Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.

So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?

like image 854
Fixpoint Avatar asked Nov 30 '10 10:11

Fixpoint


People also ask

Should you use getters and setters within a class?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value.

What's the advantage of using getters and setters?

The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement. 2.

Is it important to always define setters and getters for all the private variables?

It is not necessary to write getter or setter for all private variables. It is just a good practice. But without any public function you can not access the private data(variable) of the class.

Do getters and setters speed up compilation?

Getters and setters can speed up compilation. Getters and setters provide encapsulation of behavior. Getters and setters provide a debugging point for when a property changes at runtime.


1 Answers

The most obvious answer is side effects:

int getCost()
{
    if (cost == null) {
        calculateCost();
    }

    return cost;
}

If you need the cost, use getCost(). If you want to see if cost has been calculated, use cost.

like image 168
aib Avatar answered Sep 21 '22 12:09

aib