OOP – Understanding Abstraction in Object-Oriented Programming

abstractionencapsulationobject-oriented

I hear that Abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden.
Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.

I understand Encapsulation well… A simple example would be a Method that calculates calories based on the parameters we provide. CalculateCalories(x,y,z) Here I don't know how this method calculates calories but I can call it to calculate the calories.

Abstraction is what I am confused about. What are those techniques that Abstraction uses to help identify which specific information should be visible, and which information should be hidden? Or am I misunderstanding the concept?

Could anyone give an intuitive example?

Best Answer

In functional programming, there is a concept called Map. Map is a higher-order function that applies a function to each element in a list.

In ordinary code, you would do something like:

var list = new List<int> { 1,2,3,4,5,6 };

var newList = new List<int>();

foreach(var item in list)
{
    newList.Add(item * 2);
}

// newList --> { 2,4,6,8,10,12 }

Rather than writing a loop each time, you create a Map method:

public List<T> Map<T>(this List<T> list, Func<T,TResult> function)
{
    var newList = new List<T>()

    foreach(T item in enumeration)
    {
        newList.Add(function(item));
    }

    return newList;
}

Now, instead of writing a loop each time, you can simply write:

var list = new List<int>() { 1,2,3,4,5,6 };

var modifiedList = Map(list, x => x * 2); // { 2,4,6,8,10,12 }

and get the same result.

The Map method is an abstraction over writing a loop to modify each member of a list.


I haven't mentioned it yet, but the <T> syntax is also an abstraction. It's called generics; it means that you can write a function that can operate on different data types, instead of writing functions for each data type.

All abstraction is a form of generalization: writing code that applies to more than one specific situation.