A
A
antoshka_basenko2021-10-21 12:35:19
Java
antoshka_basenko, 2021-10-21 12:35:19

Should getters and setters be used within the class itself?

Let's say I have some class in Java, it has a private field, as well as a getter and setter for it. If I want, for example, to get the value of this field in a method of this class, should I use a getter or within the class it is customary to access it through this.field.

PS I understand that it will work this way and that, I just want to understand how it is customary to do

PSS Would it be more correct to implement method 1 or method 2? Here is an example code:

class someClass {
    private int someField;
    public int getSomeField() { return this.someField; }
    public void setSomeField(int someField) { this.someField = someField; }

    public void method1() {
        int f = this.getSomeField();
        /*остальное тело метода*/
    }

    public void method2() {
        int f = this.someField;
        /*остальное тело метода*/
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Cheremisin, 2021-10-21
@antoshka_basenko

It is more correct, of course, through getters-setters, since it was originally assumed that there is only one control point - a getter / setter.
On the other hand, everything is at the discretion of the developer, you can also directly to the field.

B
BorLaze, 2021-10-21
@BorLaze

No no and one more time no.
Well, imagine a class that works with time. The getter returns a string like "01:23:45", the setter operates with the same user-friendly format. And inside you store the time in milliseconds. What will you convert every time?
Getters/setters are an interface for working with objects of a class OUTSIDE. What's under the hood is an implementation matter, and operations INSIDE the class must go with the data and in the form defined by the architecture. And not what form the consumer of the class needs.
Well, the simplest everyday example - there is an engine, and there is some kind of speed controller with it. Should this regulator go directly to the carburetor, or should it use a special lever to press on the gas pedal?

A
AndromedaStar, 2021-10-21
@AndromedaStar

The second option will be correct, since getters and setters are the interface of your class for interacting with the outside world. And inside the methods should work with the internal state of the class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question