Encapsulation helps by insulating calling classes from changes.
Let's imagine you have a simple class that models a car engine (cause all OO examples should involve a car analogy :) ). You may have a simple field like this:
private bool engineRunning;
Simply making this field public or providing an IsEngineRunning() getter doesn't appear to be any different.
Now suppose you make your class more sophisticated, you want to remove that field and replace it with:
private bool ignitionOn;
private bool starterWasActivated;
Now if you have lots of classes accessing the old engineRunning
field you have to go and change them all (bad times).
If instead you had started with:
public bool IsEngineRunning()
{
return this.engineRunning;
}
you could now change it to :
public bool IsEngineRunning()
{
return ignitionOn && starterWasActivated;
}
and the class's interface remains the same (good times).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…