Property and Encapsulation
Asked Answered
E

4

7

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?

Escarpment answered 25/5, 2010 at 9:24 Comment(0)
N
8

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

Nomination answered 25/5, 2010 at 9:33 Comment(1)
I would like to point out that this change does not imply that the clients must be changed. It only implies that you will have to expose the engineRunning property in the same way and with the same semantics as before. The only difference is that each update to the ignition and starter properties would have to also update the engineRunning property. Depending on what is more frequently read/updates this may have positive or negative performance impact.Maharaja
K
5

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
    }
}
Kandykane answered 25/5, 2010 at 10:46 Comment(1)
This is my reason I always give. This way allows you to put in checks and validation and even error/debug logging for the more complicated properties.By
A
3

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

Aquarium answered 25/5, 2010 at 10:10 Comment(0)
C
1

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.

Celik answered 25/5, 2010 at 9:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.