我正在尝试找到一种设计模式(或 maybe an algorithm )来帮助我以更简洁的方式编写这些规则。有什么建议吗?
def get_rules(user, value):
if 500 <= value < 5000 and not user.address:
return [REQUEST_ADDRESS]
if value >= 5000:
if not user.address and not user.phone:
return [REQUEST_ADDRESS, REQUEST_PHONE]
if user.address and not user.phone:
return [REQUEST_PHONE]
if not user.address and user.phone:
return [REQUEST_ADDRESS]
# Potentially ~20 more conditions here based on various attributes of user
return [STATES.REQUEST_NONE]
注意:我不是在寻找规则引擎,因为我不想通过在 python 中添加“业务友好”DSL 来使我的代码复杂化。 Python 本身就是一种编写这些规则的简单语言。
有趣的阅读:http://martinfowler.com/bliki/RulesEngine.html (但我仍然试图远离“框架”来为我做这件事)。
最佳答案
您正在使用“if a and not b else check not a and b else check not a and not b”策略检查许多不同的组合,以确定您需要发送哪些请求组合。
相反,只检查您遗漏的内容:
missing = []
if not user.phone:
missing.append(REQUEST_PHONE)
if not user.address:
missing.append(REQUEST_ADDRESS)
return missing or [REQUEST_NONE]
关于python - 在 Python 中更简洁地表示规则 (if-else),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29379061/