Question

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?

Was it helpful?

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

OTHER TIPS

Its better to expose properties instead of member variables, because that would enable you to do all kinds of checking when setting or getting the value of the member variable.

suppose u have a member variable:

private int id;

and you have a public property:

public int ID
{
    get 
    { 
       // do something before returning
    }
    set 
    {
      // do some checking here may be limits or other kind of checking
    }
}

I'll make it short. Properties=flexibility

1 Properties are useful for creating members that You don't want to hold in a class all the time or that are aggregations/functions of existing members.

Eg. age can be output based on birthdate, canSwim can be generated from hasLimbs && floats

2 Exposing members as properties can be helpful when dealing with unexpected changes [did anybody ever predict all client's requests?] in systems with an existing database.

Eg. isAllowed is true when user is over 18yr and is cached for performance. Client wants to run the service in the US and You can return false if false is chached and check age only when cache is true

Some thoughts:

  • You can change the internal representation of your data without affecting calling classes.

    E.g. (before)

    public boolean isActive() {
        return this.is_active;
    }
    

    (after)

    public boolean isActive() {
        return this.is_active && this.approved && this.beforeDeadline;
    }
    

    This is especially important if your code is used by others (i.e. your code is 3rd-party). To a certain degree your interface/API has to remain stable. Small changes should not affect the code of other code that uses it.

  • You can have more complex operations. Consider a variable is_active. Maybe changing the value of this variable also effects other properties of the object. If you encapsulate the access in a method, you can take care of this inside this method and the caller does not have to care.

    E.g.

    public void setActive(boolean active) {
        this.is_active = active;
        this.startTimeout();
        this.updateOtherInformation();
    }
    

    It therefore enforces a certain series of actions. You do not have rely on the fact that the caller executes this actions properly. Your object will always be in a correct state.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top