Dot Net For All

Abstraction and Encapsulation – The two OOP Pillars in C#

Abstraction and Encapsulation

Hello, Till recently I was not sure what exactly is abstraction. And its importance in OOP(object oriented programming). And the top results in Google search confuse you more about abstraction principle. In this article I will be explaining both abstraction and encapsulation with relevant examples in C#.

Lets see these OOP principles one by one.

Abstraction and Encapsulation in OOP

Please make note of one point here. Abstraction is not at all related to abstract class in C# as mentioned in one of the answer in stackoverflow, and to my wonder this answer has been up-voted many number of times.

Here I will discuss the both abstraction and encapsulation in single  class example. But first lets start with the simple definition of both of these concepts.

Encapsulation – is the concept of OOP in which we hide the internal details or state of a class from the outside word. The fields or variables of the class define the state of a class. If we make these  fields public then anyone outside the class can access it and should be able to change the state of class.

This behavior  of the class can result to unexpected results and in turn result to the error in the software.

To prevent from this kind of behavior Properties are introduced in C#. Properties in C# are nothing but getter and setter methods wrapped around a private member variable.

Abstraction – 

In object Oriented programming if objects are the heart of modelling, then why bother with classes? The notion of abstraction is at the heart of matter. By grouping objects into classes we abstract a problem. Abstraction gives modelling its power and ability to generalize from a few specific cases to a host of similar cases.

Common definitions like class name and attribute name are stored once per class rather than once per instance. We can write operations once for each class, so that objects benefit from code reuse.

To explain both of these concepts, one small example is enough. Have a look at the self explanatory example as shown below

        public class Employee
        {
            private string firstName;
            private string lastName;

            public String FirstName
            {
                get { return firstName; }
                set
                {
                    if (!Regex.IsMatch(value, "^[0-9]*"))
                    {
                        firstName = value;
                    }
                    else
                    {
                        throw new ArgumentException("Numbers are not allowed");
                    }
                }
           }

            public String LastName
            {
                get { return lastName; }
                set
                {
                    if (!Regex.IsMatch(value, "^[0-9]*"))
                    {
                        lastName = value;
                    }
                    else
                    {
                        throw new ArgumentException("Numbers are not allowed");
                    }
                }
            }

            public string FullName()
            {
                return string.Format("{0} {1}", firstName, lastName);
            }
        }

The above class implements the encapsulation by implementing the two properties named FirstName and LastName.

These two properties act as wrapper around the private variables. Moreover we have logic inside the setter of the two properties. The logic defined states that neither FirstName nor LastName can have a number within themselves.

Though this is a simple logic but it prevents the user of this class to set the two properties as per the encapsulation logic of the class.

The user of the class as shown in the below code cannot have a digit in its code.

            try
            {
                Employee emp = new Employee() { FirstName = "007 James", LastName = "Bond" };
                emp.FullName();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

If Mr 007 James have to use my class, he has to remove “007” from the firstName and he is good to go.

As per the Abstraction part is concerned we have abstracted out the functionality or behavior of getting out the full name in the FullName method. This abstraction will remain same for all the object of this class. With the help of a method defined in the class we have a common behavior for all the objects of a class.

This common behavior in turn uses the states of the class.

Conclusion:

I hope I have made a point to state the object oriented concepts abstraction and encapsulation. I have clearly explained that abstraction is not at all related to the abstract classes in C#. And a simple class can be used to achieve abstraction.

References:

Object-Oriented Programming Fundamentals in C#

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview