if语句太多了 [英] Too many if statements
问题描述
我有一些话题需要讨论。我有一个24 的代码片段,如果
s / elif
s。 操作
是我自己的类,表示类似于 枚举
。
以下是代码片段:
I have some topic to discuss. I have a fragment of code with 24 if
s/elif
s. 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个类并使用多态性?我不相信它会使我的代码可维护......另一方面,一方面那些如果
s非常清楚并且它不应该难以理解如果 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 if
s are pretty clear and it shouldn't be hard to follow, on the other hand there are too many if
s.
我的问题相当一般,但是我用Python编写代码所以我不能使用像 switch
这样的结构。
My question is rather general, however I'm writing code in Python so I cannot use constructions like switch
.
你怎么看?
UPDATE :
一个重要的事情是 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
(...)
}
最好有一个默认操作以防万一,所以当你运行它时使用尝试除了
并处理异常(即相当于 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.
这篇关于if语句太多了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!