Getters/setters 提供对字段的受控访问,但为每个字段添加一个的常见做法是一种反模式。真正的问题是:访问器是否增加了价值,还是只是用额外步骤重新暴露一个公共字段?
何时 setter 是合理的
java
{
target;
{
(t < || t > )
();
.target = t;
}
{ target; }
}
这里 setter 强制执行了一个不变式 — 这是有价值的。
// Anti-pattern: "encapsulation theatre"
public class Point {
private int x, y;
public int getX() { return x; } public void setX(int x){ this.x=x; }
public int getY() { return y; } public void setY(int y){ this.y=y; }
}
// This is no safer than public fields — and now x,y can change anytime.
与其为调用者暴露状态来操纵,不如暴露 行为:
account.withdraw(100); // ✅ behavior protects the rule
// vs
account.setBalance(account.getBalance() - 100); // ❌ logic leaks to caller
每个字段上的 setter 几乎不比将字段设为公开更好 — 它给了一种虚假的封装感,同时让任何调用者都可以自由改变状态。
围绕行为进行设计("告诉,不要询问")将不变式保持在对象内部,减少耦合,并经常揭示许多字段根本不应该有 setter 的不可变性。