Advantages of Design Patterns in Web API: Strategies

In these posts I would like to point out the benefit of using a number of design patterns specifically for Web API projects. Specifically I will describe Commands, Strategies, Factories andĀ Builders. Afterwards I will look at dependency injection, mockingĀ and AutoMapper, and lastly conclude how it all works together.
Today we will take a look at Strategies and Helpers.

Strategies are a way to encapsulate a family of algorithms that can be used interchangeably. One can inject a specific strategy for specific scenario’s. You can think of encryption algorithms, different file readers, but also object parsers. A nice description can be found here on codeproject by WebBiscuit.
Helpers are opposite to Strategies; they are used to extract an algorithm that is identical in several locations, to create a single implementation.

The main benefit when implementing Web API and using the Command pattern described previously, is that you often find sets of Commands that basically do the same, but on different structures. Strategies provide you a way to extract the unique part, so you can reuse your command in several locations and simply inject the correct Strategy.
Similarly, you find that you duplicate an algorithm in several different Commands. In this case you create a Helper class with the algorithm that is injected in those different Commands.

The major benefits are:

  • Strategy: Isolate the algorithm, providing easier maintenance.
  • Strategy: Reuse Commands, decreasing duplication.
  • Helper: Reuse the algorithm, decreasing duplication and simplifying maintenance.
  • Easily test your algorithm as a single unit, mock them to simplify your Command unit tests.
Facebooktwitterredditpinterestlinkedinmail

Leave a Reply