Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many if statements

I have some topic to discuss. I have a fragment of code with 24 ifs/elifs. Operation is my own class that represents functionality similar to Enum.
Here is a fragment of code:

if operation == Operation.START:
    strategy = strategy_objects.StartObject()
elif operation == Operation.STOP:
    strategy = strategy_objects.StopObject()
elif operation == Operation.STATUS:
    strategy = strategy_objects.StatusObject()
(...)

I have concerns from readability point of view. Is is better to change it into 24 classes and use polymorphism? I am not convinced that it will make my code maintainable... From one hand those ifs are pretty clear and it shouldn't be hard to follow, on the other hand there are too many ifs.

My question is rather general, however I'm writing code in Python so I cannot use constructions like switch.

What do you think?


UPDATE:

One important thing is that StartObject(), StopObject() and StatusObject() are constructors and I wanted to assign an object to strategy reference.

like image 871
Konrad Avatar asked Jul 31 '15 14:07

Konrad


1 Answers

Starting from python 3.10

match i:
    case 1:
        print("First case")
    case 2:
        print("Second case")
    case _:
        print("Didn't match a case")

https://pakstech.com/blog/python-switch-case/

like image 73
LazerDance Avatar answered Sep 28 '22 07:09

LazerDance