Intro

In this article, we’ll take a look at why switch is almost never a good idea in OOP. We are going to look from different perspectives at how it affects the code, tests, and maintainability. Afterwards, we’ll do some refactoring on our existing code and analyse the benefits of the newly refactored code. We’ll see how almost any (no matter how long) switch can and should be converted to an elegant one-liner. All the source code used in this article can be found here, which has two branches — the un-refactored code (main) and the result after refactoring (feature/refactor-switch).

switch Is Almost Never a Good Idea

How many times have you come across some code that you need to add some changes to or modify something, and you do this?

Top
Generated by Feedzy