Which is better using private variables or public methods in a class?

Example:

private int x = 4;

public TestClass(int x) {
    this.x = x;
}

public TestClass(int x) {
    setX(x);
}

public void setX(int x) {
    this.x = x;
}

Is the first constructor more practical or the second? I ask about this because when I encapsulate my classes in IntelliJ IDEA, if I used to this.x = x, it changes it to setX(int newX);.

+4
source share
4 answers

For the most part, all personal preferences. I would use the first constructor if its value was independent of other variables. However, setter methods allow you to fulfill certain conditions before changing a variable's value. For instance:

private int x;

public TestClass(int x) {
    setX(x);
}

public void setX(int x) {
    // Some random condition depending on other variables.
    if (System.currentTimeMillis() & 1 == 0) {
        this.x = 5;
    } else {
        this.x = x;
    }
}

setter, , .

, , , , , setter, . , - setter, final .

+1

.

, , .

, , setter . , , .

+1

Self Encapsulation. . . , setter. , setter , .

0

, , . ( , ), . , .

Immutable classes are inherently thread safe and should be preferred when appropriate. So in your (admittedly superfluous) example, I would prefer to use a constructor, and I would only have a getter for the value.

IMO, having a constructor that takes a value and a setter that sets the same value, is a flavor of the code if it doesn't smell.

0
source

Source: https://habr.com/ru/post/1675855/


All Articles