使用getters()或在POJO中使用直接字段访问?

non*_*tor 2 java

给定一个简单的POJO确实会产生影响,或者使用以下任何一种方法可能会产生副作用:

total = getPriorAmount() + getCurrentAmount();
Run Code Online (Sandbox Code Playgroud)

要么

total = this.priorAmount + this.currentAmount;
Run Code Online (Sandbox Code Playgroud)

在POJO中使用时.

Chs*_*y76 7

总有副作用:-)

在这种情况下,它可能是一个简单的POJO 现在.但是在2周(月,年)中,有人可能会为你的getter方法添加一些条件逻辑,并且getCurrentAmount()可能不再相同this.currentAmount(后者可能是最后一个已知的"缓存"值,例如getter方法可能会重新计算它).

这就是为什么编码接口总是一个好主意,即使这种情况下的接口是对象本身(例如它的公共getter).