How to Refactor a Switch Statement with Object Composition in Angular

Using Creational Patterns like Factory Method to refactor switch statements in Angular

Itchimonji
CP Massive Programming

--

Programmers try to avoid switch statements because switches break the rule of the Open-Closed-Principle. Also, continuously extending the switch statement with more clauses leads to a high maintenance effort, as we need to modify the written code every time we extend it. Maybe our working unit tests will fail after the change. We might need to fix our business logic and tests every time — what a nightmare…

“The Problem with such duplicate switches is that, whenever you add a clause, you have to find all the switches and update them.” (Martin Fowler, [Refactoring])

Why do we use switch statements?

We use them because switch statements work the way our brain works. If we have to implement a selection of different things — like a selection of themes, or types of tea/coffee we want to cook, or a selection of cars we want to buy with our saved money — the logical way is to implement different junctions to map all the possibilities: we code like a flow.

Example code

--

--

Itchimonji
CP Massive Programming

Freelancer | Site Reliability Engineer (DevOps) / Kubernetes (CKAD) | Full Stack Software Engineer | https://patrick-eichler.com/links