Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

oop - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...