Member-only story
BETTER SOFTWARE DESIGN
Replacing If-Else With Commands and Handlers
How to easily replace if-else statements. And no, a switch is not a suitable substitute.

If you want to learn how I use commands and handlers to keep my code neat and tidy, read on. It’s not about avoiding if-elseif-else
. It’s about finding a more suitable approach.
Bear in mind that no single approach will ever get rid of traditional branch-based programming. You need to build a repository of techniques to draw from.
The method we’ll walk thru now is just one of many.
if-else
is, at its very core, not bad. It’s merely just a hammer and nail situation we got going. In programming 101, you’ll learn conditional statements, and lots of developers never mature their practices beyond that.
But, if-else
and switch
are often not ideal. Better approaches, such as polymorphic execution and dictionaries, are typically neglected.
We want to avoid traditional, conditional branches.
I’ve written an article proposing a way of replacing conditional branching with polymorphic execution. To get some context, I’ll briefly repeat some of the earlier article examples before we deep dive into commands and handlers.
Here’s the example of what we’d like to avoid: Nasty, difficult to extend, branching on a discrete value.

Besides the freakish use of if-elseif-else
, the main issue is you need to add a branch for every new update reason. A clear violation of the Open/Closed and Single Responsibility principles.
Each branch can basically be converted to its own command and corresponding handlers.
Let’s take a look at how that’s possible.
🔔 Want more articles like this? Sign up here.