Functions redux (part 1)

What are functions for?

Abstraction

Abstraction is about hiding or ignoring certain details.

Adding sheep

If I have two πŸ‘ and buy two more. How many do I have?

πŸ‘πŸ‘ + πŸ‘πŸ‘ = πŸ‘πŸ‘πŸ‘πŸ‘

Adding cows

If I have two πŸ„ and buy two more. How many do I have?

πŸ„πŸ„ + πŸ„πŸ„ = πŸ„πŸ„πŸ„πŸ„

Abstraction

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.

Move up a level

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 are a kind of abstraction

Functions hide how they work letting you focus on what they do.

Average two numbers

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

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.

Why abstract?

  • Remove duplication

  • Name computations

Remove duplication

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.

Name a computation

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.

Recipe exercise

Take apple pie and cherry pie recipes and factor out the common bits by creating abstractions.

Assignment

Up next

Function redux, part 2