The Strategy Pattern in Node

The strategy pattern is a very useful way to have multiple concurrent solutions to a problem. Given some condition, we need to pick how we solve it.

In the simplest form, an if/else construct can do this for us.

if(someCondition){doFirstOption();}else{doSecondOption();}

The problem with the if/else scenario is that it doesn’t scale. As our systems grow, we need a better way to inject new policies. We may have different strategies required for development, automated testing, and production environments. This is where the strategy pattern becomes so effective.

The business logic

In our application, we have different login policies.

When running on localhost, passwords will be stored in the database.

When running under an automated test, the password is always “test”.

When running in production, use active directory validate users.

Strategy contract

If we were writing this solution in a static language, we would write an interface. It would look something like this.

Registering strategies

Order matters when registering our strategies! Since we are looking at different values for which strategy to select, we could end up with multiple valid strategies. The test strategy is going to check the NODE_ENV environment variable. Our other strategies are going to check the LOGIN_METHOD environment variable.