它们是相同的逻辑,但我想知道在软件工程或最佳编码实践的任何维度上,两者之间的可读性/未来迭代等方面有什么更好。
def is_setting_enabled(a):
if a == "green":
return is_green_setting_enabled()
if a == "blue":
return is_blue_setting_enabled()
if a == "yellow":
return is_yellow_setting_enabled()
return False
或
def is_setting_enabled(a):
if a == "green":
return is_green_setting_enabled()
elif a == "blue":
return is_blue_setting_enabled()
elif a == "yellow":
return is_yellow_setting_enabled()
return False
如果我都不说呢:
color_fn_map = {
"green": is_green_setting_enabled,
"blue": is_blue_setting_enabled,
"yellow": is_yellow_setting_enabled,
}
def is_setting_enabled(a):
return color_fn_map.get(a, lambda: False)()
易于扩展,映射清晰,如果你最终有很多颜色,这将比if更快。
我不认为这绝对更好,但我更喜欢有很多可能性的时候。