Template Method rocks but Higher Order Function can do the trick

We can pass the filesystem helpers result as a function to the chooseFile function.

Remember these conditionals?Let’s split them into two functions:Now let’s turn our old chooseFile into a Higher Order Function:Now our chooseFile function receives a finder function as a parameter and returns another function.

It doesn’t know the finder fetches the files within a folder and is open for extension since it allows any finder to be passed in.

To those unfamiliar with ES6 arrow function syntax, this is the same as:https://gist.

github.

com/MarcoNicolodi/4e4941deccfa28a5ac8863a9e3ed8769To avoid having to pass the finder every time you need to choose a file, we can leverage function composition:Here’s the whole solution:SummaryOur functional solution using a Higher Order Function achieves the same as our OOP solution using the Template Method design pattern.

It’s open for extension and closed for modification, since it accepts any finder, and has a single responsibility, since it will not change if a finder requirement changes.

Higher Order Function is a basic concept in functional programming, and you use it a lot if you code in JavaScript.

For more details you can dive deeper with the amazing Eloquent Javascript Ebook.

.. More details

Leave a Reply