太多的 if 语句 [英] Too many if statements

查看:24
本文介绍了太多的 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 个类并使用 多态 是否更好?我不相信它会使我的代码可维护......一方面,那些 if 很清楚,应该不难理解,另一方面有太多 ifs.

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.

这篇关于太多的 if 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆