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
 
yaser profile image
Yaser Al-Najjar • Edited

That's why we never have switch in Python 😁

And, the dictionary is always a better and cleaner alternative for the ugly switch.

def my_switcher(x):
    return {
        'a': 1,
        'b': 2,
    }[x]


print(my_switcher('a'))
print(my_switcher('b'))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Whenever I think about why I don't like a certain way a language does something, I realize it always goes back to my love for Python. That language has ruined me. haha

Collapse
 
yaser profile image
Yaser Al-Najjar

❤ for the utmost ruining lang.

Collapse
 
kylegalbraith profile image
Kyle Galbraith

Really love this pattern. I have seen various approaches to the default case that vary across languages.

Collapse
 
lysofdev profile image
Esteban Hernández

How would you handle a default case in this?

My though is to add || defaultValue at the end since a failure to match any property will return undefined. Thoughts?

Collapse
 
yaser profile image
Yaser Al-Najjar • Edited

That would be handy using a try except:

def my_switcher(x):
    switches = {
        'a': 1,
        'b': 2,
    }
    default = 3

    try:
        result = switches[x]
    except KeyError:
        result = default

    return result



print(my_switcher('a'))
print(my_switcher('b'))
print(my_switcher('c'))

I added the extra default variable just to make the code self explanatory.

EDIT: Bad solution, look at the other comments.

Thread Thread
 
rhymes profile image
rhymes

You can also use defaultdict in the standard library :D

Thread Thread
 
pedromendes96 profile image
Pedro Mendes • Edited

This is clean :D

Thread Thread
 
lysofdev profile image
Esteban Hernández

This is the answer to this entire thread.

Thread Thread
 
yaser profile image
Yaser Al-Najjar

@rhymes and @pedromendes96 got it better than me 😁

Collapse
 
gidrek profile image
Giovanni Cortés • Edited

Elixir :)

def my_switcher("a"), do: 1
def my_switcher("b"), do: 2
def my_switcher(), do: 3

iex(1)> Example.my_switcher("a")
1
iex(2)> Example.my_switcher("b")
2
iex(3)> Example.my_switcher()
3
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kip13 profile image
kip

Pattern matching to the rescue ?

Thread Thread
 
cescquintero profile image
Francisco Quintero 🇨🇴

Isn't this feature called method overloading ? 🤔

Thread Thread
 
gidrek profile image
Giovanni Cortés

No, because overloading is have same parameters with different types, but in patter matching you can have the same type and number of parameters but differs in the content. For example, here!

Collapse
 
seanwash profile image
Sean Washington

I quite like cond as well for certain situations as well.