Search code examples
ooppropertiesencapsulationmember-variables

Property and Encapsulation


Following is a question regarding using properties in class.

I have been using public properties instead of exposing member variables publically. Majority advise that this approach helps encapsulation. However, I don’t understand the encapsulation advantage by making it a property.

many people donot know the real reason for using properties. They just do it as part of coding standard.

Can someone clearly explain how a property is better than public member variable and how it improves encapsulation?


Solution

  • 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).