Abstraction is about hiding or ignoring certain details.
If I have two π and buy two more. How many do I have?
ππ + ππ = ππππ
If I have two π and buy two more. How many do I have?
ππ + ππ = ππππ
Compared to thinking in terms of π and π, numbers are an abtraction.
2 + 2 = 4 regardless of what things we are counting.
If you understand how 2 + 2 = 4 is an answer to both the π and π questions, then, congratulations, you know how to deal with abstraction.
While abstract compared to π and π, 2 + 2 is a concrete math problem in that it involves specific numbers.
We could know the answer to 2 + 2 without knowing how to add any two numbers.
Even someting as simple as βcounting onβ is an abstract procedure for doing addition that hides the details of what numbers you will apply it to.
Functions hide how they work letting you focus on what they do.
Concrete:
const avg = (10 + 20) / 2
Abstract:
const avg = average(10, 20)
Presumably the function average
does the same thing as the concrete expression but we donβt have to worry about that when we see it being called.
Inside the abstraction, things areβsuprise!βabstract.
We need to define the operation not in terms of specific values but abstracted, named values, a.k.a. variables.
const average = (a, b) => (a + b) / 2;
This function can compute the average of any two numbers.
Remove duplication
Name computations
When we write use a function multiple times, that removes duplication.
The code in the function is only written in one place and used from everywhere we call it.
Sometimes we introduce a function even if it will only be used in one place because it lets us give a name to what the function is doing.
If we choose our names well, the name conveys useful information about what is going on in our program.
Take apple pie and cherry pie recipes and factor out the common bits by creating abstractions.