SIGN UP MEMBER LOGIN:    
ARTICLE

The first pillar of object-oriented programming - Encapsulation

Posted by Amr Monjid Articles | OOP/OOD May 09, 2008
In this article we will start with Encapsulation, the first pillar of OOPS, you will learn the benefits of encapsulation and why to use it, you will learn how to enforce encapsulation by using (accessor and mutator) and by using properties.
Reader Level:

Introduction:

One of the benefits of encapsulation is data protection, so by using encapsulation when the object user want to change or obtain the value of any entity he must ask first, so we can make all validation processes we need.
 
Encapsulation also gives you the ability to hide unnecessary implementation details from the object user. It simplifies the programming tasks instead of writing many lines of code each time we want the object do the same functionality.
 
Why Encapsulation?

To understand the importance of encapsulation let us see the following example:

public class Employee

{

    public string Name;

    public int Age;

}
 

//creating the object

Employee firstEmp = new Employee(); 

firstEmp.Name = "Amr!?Ashush";
firstEmp.Age = 50000; 

The problem start when the object user set the values of the Employee class, as you saw the Name variable = Amr!?Ashush and the (!?) characters can not be in real world names, and the Employee age also can not be 50000.
 
Encapsulation gives you the ability to validate the values before the object user change or obtain the value.

There is two ways to create a validation process:

  1. Using Accessors and Mutators.
  2. Using properties.

Using Accessors and Mutators:
 
we start first by set the class variables as private then the object user can not change or obtain the values directly.

public class Employee

{

    private string Name;

    private int Age;

}
 

//creating the object

Employee firstEmp = new Employee(); 

 

//Compile time error

firstEmp.Name = "Amr!?Ashush";
firstEmp.Age = 50000; 
 
We will now add tow methods one to get the value (Accessor) and the other to set the value (Mutator).
 
These methods will allow us to validate the values before the object user change or obtain the value.

Our employee class will be as follow:

public class Employee

{

    private string name;

    private int age;

 

    //Age Accessor

    public int GetAge()

    { return age; }

   

    //Age Mutator

    public void SetAge(int age)

    {

         if(age > 60)

        {

             Consol.WriteLine("Employee age can not be more than 60");

        }

        else

        {

            this.age = age;

        }

    }

 

    //Name Accessor

    public string GetName()

    { return name; }

 

    //Name Mutator

    public void SetName(string name)

    {

        if (name.IndexOf('?') > 0)

        {

             Consol.WriteLine("Illegal Character can not be in the name");

        }

        else

        {

            this.name = name;

        }

    }
}

Now the object user must go through the accessor and mutator in order to change or obtain the value, so he can not set illegal value to the entity.

//creating the object

Employee firstEmp = new Employee();

 

//use mutators (it's OK)

firstEmp.SetName("Amr");

firstEmp.SetAge("23");

 

//use accessors to get the values

string EmployeeName = firstEmp.GetName();

int EmployeeAge = first Emp.GetAge();
 

//try to set illegal values (Error)

firstEmp.SetName("Amr?");

firstEmp.SetAge(100); 

The result:


Illegal Character can not be in the name 

Employee age can not be more than 60
 
Using Properties:


You can enforce encapsulation by using properties which allow you to access the data in the class.

A single property gives you the ability to set or obtain the value of a variable instead of using tow different methods as accessor and mutator.
 
Example:

public class Employee

{

    private string name;

    private int age;

 

    //the name property

    public string Name

    {

        //the accessor

        get{ return name; }

 

        //the mutator

        set

        { name = value; }

    }

}
 

//creating the object

Employee firstEmp = new Employee();

 

//using the property to set value

firstEmp.Name = "Amr";

 

//using the property to get value

string n = firstEmp.Name;

 

We can use the properties to validate data as follow:

 

//the name property

public string Name

{

    //the accessor

    get{ return name; }

 

    //the mutator

    set

    {

         if(name.IndexOf('?') > 0)

        {

             Consol.WriteLine("Illegal Character can not be in the name");

        }

        else

        {

            name = value;

        }

    }

} 

Read Only Properties:
 
You create a read only property by removing the set block as follow:

//Read only property

public string Name

{

    //the accessor

    get{ return name; }

}
 
So if we try to set the value of the name we will get a compile time error

//Compile time error

firstEmp.Name = "Amr";
 
Static properties:
 
you can create static properties which can accessed only from the class level. Note that the static properties can operate only static data.

public class Employee

{

    private static string firmName;

 

    public static string FirmName

    {

        get { return firmName; }

        set { firmName = value; }

    }

}
 
We are done now, thank you for reading,

see you.

Login to add your contents and source code to this article
share this article :
post comment
 

Thanks for sharing.

Posted by Itz Irshad Oct 04, 2011

Thanks for such a nice explanation. I have one doubt. In "Using Properties':Example,the code is : if(name.IndexOf('?') > 0) {Consol.WriteLine("Illegal Character can not be in the name");} But its throwing error.As per my understanding,it should be something like this: if(value.IndexOf('?') > 0) {Consol.WriteLine("Illegal Character can not be in the name");} Please correct me if I am wrong.

Posted by Hina Jul 26, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Become a Sponsor