Why use get and set in Java?

Question:

I learned in college a while ago that you should always use getters and setters to access values ​​on an object and I've heard it's for security reasons.

So I ended up always using it and seeing other people using it, until I started programming Android and noticed that Google says NOT to use it, for performance reasons (only in the case of Android).

So what's the use of get and set ? Is it just for good practices? I don't understand why of good practice in this case. What influences me to use or not?

Is the security question real? It seems a little illogical to say this.

Example:

pessoa.getNome(); //acessando uma variavel privada com get

pessoa.nome; //acessando uma variavel publica diretamente

Answer:

"Security" in this case only refers to a programmer accidentally accessing a variable in a way other than that intended by the class author (not necessarily a different programmer). I'll give you an example:

class Fração {
    int numerador;
    int denominador; // Não pode ser zero

    public int calcular() { return numerador / denominador; }
}

If you can access variables directly, you must always remember that the denominador cannot be zero. But what if you forget? At the time, nothing will happen… But later on, when another part of the code calls calcular , it will give a division-by-zero error. At a time you're not expecting it, and it's going to look like the call to the calculation caused the exception (making it harder to debug).

Now, let's say you change the visibility of this variable to private and create a getter and a setter :

class Fração {
    int numerador;
    private int denominador; // Não pode ser zero

    public int getDenominador() {
        return denominador;
    }

    public void setDenominador(int denominador) {
        if ( denominador == 0 )
            throw new IllegalArgumentException("O denominador não pode ser zero!");
        this.denominador = denominador;
    }

    public int calcular() { return numerador / denominador; }
}

In that case, you keep having to remember that you can't pass zero, but what if you forget, what changes? Changes that the exception will be thrown immediately when trying to assign the value, pointing out the exact line of code where the error occurred, so it's much easier to identify and fix the error.

Note that, in the case of numerador , it doesn't make sense to create getter and setter , you can do it (by convention) or not.

There are other benefits of having an extra layer of abstraction around your variables, for example allowing you to change your class's internal representation while keeping your contract constant. These benefits are most significant when you want to have a stable API, or when you're programming in a large team where not everyone knows exactly what each other's code does.

In general, the loss of performance in using an extra method is negligible given the benefits that this technique brings. However, if you're always creating getters and setters "because I learned that's how it has to be", but you never or rarely need to validate a field, or refactor the implementation, or have no one but yourself consuming your API, then Things change: not only do you spend more time writing a bunch of useless code, but the small performance losses over the course of the entire project build up, which can make a significant difference (I doubt it, it sounds like micro-optimization, but it will. know… maybe Android's Java isn't as optimized to handle this case as the official JVM).

I believe this is the reason behind this recommendation not to use it on Android. Is the code "less secure"? He is. But it's just a matter of being more careful when programming (and that's always "good practice"). As for the final product, this in itself doesn't cause any code vulnerabilities or anything like that.

Scroll to Top