DEV Community

Discussion on: I've never become overly convinced that switch statements are that much cleaner than `if else if else if else if else`

scott_yeatts profile image
Scott Yeatts

I could easily see if I'm dealing with a returnable statement over 20 lines where the return value is based on multiple conditionals or is impossible to keep in your head all at once, that return early and often would be a good backstop to make sure you know what is returned and when... And I HAVE run into code like this in the wild that I couldn't refactor entirely for stability, but I could make sure it was readable, and that did involve applying Exit Early.

With new code or things I could refactor, I would have to go with Uncle Bob's rule from Clean Code

The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.

If you're dealing with multiple nested conditionals or the triangle of death where nesting is making the indents move out and out until your code looks like an arrow pointing off to the right, then the function is probably just too big and needs to be broken up for maintainability...

But now we're going to get so far off the topic we'll need to write a whole new topic to keep this up hahaha!

Thread Thread
cheetah100 profile image
Peter Harrison

I broadly agree with the idea that functions should be small, but care should be taken not to break up logically sequential operations that really belong together just to comply with this principle.

More important to me is that a function should have one clearly defined purpose and not mash together a bunch of logically separate operations.

Switches tend to be used for doing multiple separate things based on some value. It is not always bad, but I always evaluate whether there is a better more extensible way to do it than a switch when I see it.

I'm not saying I've never used a switch, but it is generally not one I use unless there is a really good reason.