Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

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.

Nicklas Millard
Level Up Coding
Published in
8 min readSep 24, 2020

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.

Complicated, headache-inducing branching

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.

Using commands and handlers to simplify your application.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Written by Nicklas Millard

I mostly write to "future me" sharing what I learn and my opinion on software development practices. youtube.com/@nmillard | open for contracts in Jan 2026.

Responses (43)

Write a response