if 语句过多

问题描述

我有一些话题要讨论.我有一段代码,包含 24 个 ifs/elifs.Operation 是我自己的类,表示类似于 Enum 的功能.
这是一段代码:

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()
(...)

从可读性的角度来看,我有一些顾虑.将其更改为 24 个类并使用 polymorphism 会更好吗?我不相信它会使我的代码可维护......一方面这些 if 非常清楚,应该不难理解,另一方面有太多 如果s.

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.

我的问题相当笼统,但是我正在用 Python 编写代码,所以我不能使用像 开关.

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

你怎么看?

更新:

重要的一点是 StartObject()StopObject()StatusObject() 是构造函数,我想将一个对象分配给策略参考.

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


解决方案

你可以使用字典.字典存储引用,这意味着函数完全可以使用,如下所示:

You could possibly use a dictionary. Dictionaries store references, which means functions are perfectly viable to use, like so:

operationFuncs = {
    Operation.START: strategy_objects.StartObject
    Operation.STOP: strategy_objects.StopObject
    Operation.STATUS: strategy_objects.StatusObject
    (...)                  
}

最好有一个默认操作以防万一,因此当您运行它时,请使用 try except 并处理异常(即相当于您的 else 子句)

It's good to have a default operation just in case, so when you run it use a try except and handle the exception (ie. the equivalent of your else clause)

try:
    strategy = operationFuncs[operation]()
except KeyError:
    strategy = strategy_objects.DefaultObject()

或者使用字典的 get 方法,如果没有找到您提供的键,您可以使用该方法指定默认值.

Alternatively use a dictionary's get method, which allows you to specify a default if the key you provide isn't found.

strategy = operationFuncs.get(operation(), DefaultObject())

请注意,将它们存储在字典中时不包括括号,只在调用字典时使用它们.这也要求 Operation.START 是可散列的,但应该是这种情况,因为您将其描述为类似于 ENUM 的类.

Note that you don't include the parentheses when storing them in the dictionary, you just use them when calling your dictionary. Also this requires that Operation.START be hashable, but that should be the case since you described it as a class similar to an ENUM.

相关文章