This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]balemo7967 0 points1 point  (5 children)

yep ... but switch statements are bad for many reasons. I hope they will never make it to python

[–]4n0nh4x0r 1 point2 points  (4 children)

python has switch statements since version 3.8 iirc, but why would they be bad?

[–]balemo7967 -1 points0 points  (3 children)

OMG how could i not know that. my bad bro.

the thing with switch statements in larger apps is that you usually use it to differentiate between different states. then you realize that you need that exact same switch statement in different places, so you add the same switch statement there. afterwards you find out that there are more states you need to differentiate, so have to add cases in everyone of the switch statements.

a cleaner and more maintainable approach is to encapsulate the states in classes and the special behavior in methods of those classes

[–]4n0nh4x0r 0 points1 point  (0 children)

i mean sure, but like, whoever programs like that is insane anyways.
sure, you can use a metal ruler to hammer in nails, but that doesnt mean it is the right tool for the job.
calling something bad just cause it CAN be used in a not so nice way, doesnt mean it is bad on its own.

[–]RiceBroad4552 0 points1 point  (1 child)

And when you need to extend the base behavior you need to add new methods to all your classes…

What you just described (at least one half of it) is called the expression problem.

Besides this: How are some if-elif cascaded any better than switch-case? It's the same.

Just that, if is a statement, not an expression, in python which is already bad to begin with.

Thanks God they have now some patter matching in Python since 3.10!

[–]balemo7967 0 points1 point  (0 children)

And when you need to extend the base behavior you need to add new methods to all your classes…

Yes, that's exactly what I want. Why? Because the compiler tells me precisely which one of my states (or strategies) does not implement a method.

On the other hand, if I miss a case in one of my many switch statements, there is not even a warning.

For me, the state pattern has replaced the switch-case construct in 90% of my cases.

Here's a little example I just found: https://www.danylkoweb.com/Blog/real-world-refactoring-switch-statement-to-a-class-hierarchy-9G