Avoid ugly if / else blocks and make your code modular with Strategy

Click for: original source

Iskander Samatov is this introduction into Strategy design pattern and JavaScript. One particular piece of syntax that is unlikely to ever change in ES6 is if / else and switch statements.

The Strategy pattern was popularized by GoF (Gang of Four) and is a great tool for adding mutable, interchangeable parts to certain pieces of your application logic.

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

It belongs to Behavioral pattern family. This family addresses responsibilities of objects in an application and how they communicate between them at runtime.

Strategy implements the variable parts of the functionality with an agreed upon interface for otherwise generic object which we call “Context”. The context uses different strategies to perform a certain task based on the client’s invocation.

Think of the set of strategies as a toolbox and the context as a craftsman. The craftsman uses a different tool depending on the job. But in this case, all the tools have the same type of instructions on how to use them.

The code analysis for Passport.js library is also included with example code and charts explaining the pattern. Nice one!

[Read More]

Tags web-development open-source programming