Avoid If-Else Statements and write cleaner code with the Strategy Pattern

Coffee Techtalks
3 min readJul 23, 2023

--

Today, we will discuss one of the most common use cases where we end up writing if-else statements because they come to mind first.

There are numerous ways to avoid writing if-else statements based on our scenarios, following the SOLID principles, regardless of the technology we are using.

In this example, I am using TypeScript, but the same strategy can be applied in any programming language.

So, let’s begin…

Take a look at the code below, and how many of you would deny that we haven’t encountered a scenario like this while coding.

If Else Problem Statement

I know you would agree; we often do it. Now, the question is, what if any other conditions come up in the near future?

We will end up messing with the code…

I came across a behavioural design pattern that I believe is best suited to handle such scenarios. It may vary based on the requirements and approach we take.

Applying the Strategy Pattern

The Strategy Pattern allows us to define the behaviour of different objects and select it at runtime.

First lets create the interfaces and their concrete classes:

Strategy Pattern — Interface and concrete classes

Now, if any other condition is added in the near future, we will simply create another class, and there is no need to modify the existing code. This way, the code will follow the Open/Closed Principle, as it is open for extension but closed for modification.

Now, we will write a method to retrieve the best-suited strategy.

There are many ways we can implement this, such as using switch cases, a hash map, or a for loop. The choice depends on the specific context and requirements.

I have applied all of these methods to provide more clarity in terms of implementation. You can choose the one that best fits your requirements.

1. Switch cases:

Strategy Pattern — Switch case

When to choose:

  • Suitable for a small or fixed number of cases.
  • When there is a direct mapping to different strategies.

2. Hash Map:

Strategy Pattern — Hash map

When to choose:

  • More scalable and maintainable for loarge number of conditions.
  • Allows addition and removal of different strategies at runtime.

3. For Loop:

Strategy Pattern — For loop

When to choose:

  • When a common operation has to be applied to different strategies without explicitly knowing their types.

I hope you found this article helpful. Please share your thoughts and comment on how you would solve this problem statement if you have a different approach.

Happy learning!

--

--