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`

Collapse
 
kunde21 profile image
Chad Kunde

This entirely depends upon the language in which I'm working.

I'm pretty gun-shy about switches in C, especially when they are interacting with macros. Pre-processing magic is a nightmare to debug, especially when a typo accidentally eats the break.

Python I don't mind the ifelse design as much That's usually for data science-y code, so readability is rarely a high priority.

Go I'll use switch quite often. Between the assumed break and explicit fallthrough, it's just easier to read than the sibling in C. There's a few ways to make things easier and easily identified patterns. One of my favorite is a simple string check:

func something(multiple, required, variables string) error {
    switch ""{
        case multiple, required, variables:
            return errors.Errorf("all variables required %q %q %q", multiple, required, variables)
    }
    // brilliant logic here
}

I think Swift has a similar style switch statement, too, that is more useful that the default C switch design. (Could be wrong, I don't write Swift)