views:

130

answers:

6

Hi guys,

currently I am thinking about data encapsulation in C# and I am a little bit confused. Years ago, when I started to learn programing with C++, my professor told me: - "Create a class and hide it data members, so it can't be manipulated directly from outside"

Example: You are parsing an XML file and store the parsed data into some data members inside the parser class.

Now, when I am looking at C#. You have there properties. This feature makes the internal state / internal data of a class visible to outside. There is no encapsulation anymore. Right?

private string _mystring;
public string MyString
{
  get {return _mystring;}
  set {_mystring = value;}
}

From my point of view there is no difference between making data members public or having public properties, which have getters and setters, where you pass your private data members through.

Can someone explaing me that please?

Thanks

A: 

The benefit of properties is that later on, you could decide to add validation etc to the setter method, or make the getter method do some calculation or caching, and none of the code that already calls your property would need to change - since the class' interface remained stable

Rob Fonseca-Ensor
+7  A: 

The private data is encapsulated by the property itself. The only way to access the data is through the property.

In your situation above, there is little reason to use the property. However, if you later need to add some validation, you can, without breaking the API, ie::

private string _mystring;
public string MyString
{
  get {return _mystring;}
  set 
  {
      if (IsAcceptableInput(value))
         _mystring = value;
  }
}

Remember that a Property, in .NET, is really just a cleaner syntax for 2 methods - one method for the property get section, and one for the property set section. It provides all of the same encapsulation as a pair of methods in C++, but a (arguably) nicer syntax for usage.

Reed Copsey
Thanks a lot. This made a few things clear.
Ferhat
A: 

There still is data encapsulation, if you need it to be. Encapsulating data is not about hiding it from the client of the class or making it unaccessible, it's about ensuring a consistent interface and internal object state.

Let's say you have an object representing a stick shift car, and a property to set the speed. You probably know that you should shift gears in between speed intervals, so that's where encapsulation comes in.

Instead of simply making the property public, thus allowing public access without any verification, you can use property getters and setters in C#:

class StickShiftCar : Car
{
    public int MilesPerHour
    {
        get {return this._milesPerHour;}

        set 
        {
          if (vaule < 20)
              this._gearPosition = 1;
          else if (value > 30)
              this._gearPosition = 2;
          ...
          ...
          this._milesPerHour = value;
  }
}

While this example is not necessarily compilable, I am sure you catch my drift.

Jim Brissom
+2  A: 

Well so properties aren't the wild west you are taking them to be at a first glance. The unfortunate truth of OOP is that a lot of your methods are getters and setters, and properties are just a way to make this easier to write. Also you control what you'd like the property to allow someone to do. You can make a property readable but not writable, like so:

private string _mystring;
public string MyString
{
  get {return _mystring;}
}

Or as mentioned by Reed you can have your set method do a transformation or checking of any amount of complexity. For instance something like

private long myPrime;
public long Prime {
   get { return myPrime; }
   set { 
     if (prime(value) {
        myPrime = prime;
     }
     else {
        //throw an error or do nothing
     }
   }
}

You generally have all the value you get from encapsulation, with some syntactic sugar to make some common tasks easier. You can do the same thing properties do in other languages, it just looks different.

Aurojit Panda
+1 I was just typing the same thing :)
skajfes
A: 

Looking a bit deeper, why did your professor tell you to encapsulate? Just because it is the proper object-oriented design? Why is that the proper way? Programming languages and paradigms are just a way of coping with the complexity of getting a processor to run our code in an understandable way. There are two readers of code, the machine and humans. The machine will happily load data from, or branch to, any address in the memory space. We humans on the other hand like to think of "things". Our brains deal with "things" that have attributes or that perform actions. A lion will eat you, a spear can defend you, a lion is furry, a spear is pointy. So we can understand programs if they are modeled as "things". Properties are supposed to model the attributes of a thing, and methods are supposed to model the things actions. In practice it can become quite fuzzy and everything cannot be modeled as a real world action, but the effort to do so, when done well, can make a program understandable.

verisimilidude
A: 

You may be missing the fact that you don't have to have properties to correspond to all class member fields. You can decide which properties to add to your class, and whether or not they will be accessible outside of the class.

John Saunders