Thursday, September 11, 2014

JavaScript Patterns: Functions as abstractions

How can we use functions to create abstractions?

We will create a variable called “work” and we want that variable to point to a function.
The purpose of this function is to abstract the way some sort of operation needs to be performed.
We need to do some work and we want to wrap that code inside of a function and assign it to a variable called “work”.
And the only work we’ll do here is something really simple.

“Working hard...” should appear in our console when we run this program.

And it works. So now let’s raise the level of abstraction.
Let’s create another variable called “doWork”. This one is going to be a function and it will take a parameter called “f”. “doWork” expects that “f” will be another function. Something that will be invoked.



If we invoke “doWork” and we pass in our “work” variable that happens to point to a function. All of this should still work and we should see “Working hard...” in our console.
Why we are doing this?
Why is that useful?
Why we don’t call the function “work” directly? Instead of creating another function to invoke “work”.
The all idea here is to provide some abstraction. Maybe “doWork” represents some routine that can add retry logic or that can add value perhaps by logging.
Log when “work” starts, when “work” ends, or even log errors while executing “work”.



This is just a common pattern used in JavaScript where we use the function as the basis for an abstraction.
Functions that do work. Functions that execute work. Passing functions to other functions.

Because “doWork” is a generic function that tells us when something is started or ended and also some error handling. And we can reuse it to perform different functions.

No comments:

Post a Comment