What is the correct way to change the value of an already created instance variable?

If I have an instance variable that has personal visibility, should I use the installer to change its value or just change the value directly?

The instance variable in this example will only ever be changed in this class, and thus the installer will be closed. I assume that using a setter is the right way, as it localizes how / when it is changed, but this is just something that somehow calls me by mistake!

Please see below code which may help convey my question more clear

public class A {

private int i;

public A() {
   i = 5
}

private void doSomeCalculationsA() {
   //work done here which results in the value of i being directly changed
   i = 7
}

private void doSomeCalculationsB() {
   //work done here which results in change value of i being changed via the setter
   setI(5)
}

private void setI(int newValue) {
   i = newValue;
}

}
+3
source share
10 answers

, . setI - , . , - , , YAGNI - .

" , , , , ".

+2

/getter, - /.

+1

- . , . , , . , .

, - ( ), . . , , , - , . , , , .

+1

setter/getter - Java POJO, setter

0

(.. , ), . accessor/mutators.

0

. , , .

0

, . , ArrayList size add remove, . , .

0

- , , - , , - (, )

, - "" , , , .

, .

0

, , . , , , , , , , . IDE, IntelliSense , IMHO , . .

0

The main reason I will use the method is that one variable is associated with a second variable that must be changed at the same time (think about problems with threads and concurrency).

0
source

All Articles