Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
Lijo Avatar asked May 25 '10 09:05

Lijo


People also ask

What is encapsulation in real estate?

A method of controlling an environmentally hazardous substance contamination by sealing it off. © Copyright 2022 RealEstateWords.com | All rights reserved.

How do properties help provide encapsulation?

Properties allow clients to access class state as if they were accessing member fields directly, while actually implementing that access through a class method. This is ideal. The client wants direct access to the state of the object and does not want to work with methods.

What is encapsulation in Java?

Encapsulation in Java is the process by which data (variables) and the code that acts upon them (methods) are integrated as a single unit. By encapsulating a class's variables, other classes cannot access them, and only the methods of the class can access them.

Why properties are used in C#?

Properties are used to restrict direct access to member variables of a class. Abstraction is maintained using properties. Whenever you want to instantiate an object and set data to it's member variables using property you can check some conditions whether the value will be set to the member variable or not.


1 Answers

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

like image 131
Paolo Avatar answered Sep 18 '22 03:09

Paolo