【发布时间】:2017-11-14 14:38:55
【问题描述】:
我需要编写一个 IF 子句(我们使用的是 Java 8)。相关变量为group、privilege、role、level 和class。在某些情况下需要执行action。我用以下方式编写了算法:
if (group == G1) {
if (privilege == P1) {
// Perform the action if a user has this particular privilege
perform_action_and_exit();
} else {
if (role == R1) {
if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
perform_action_and_exit();
}
// Ignore other combinations of level and class
}
// Ignore other roles
}
} else {
// Perform the action for any group other than G1
perform_action_and_exit();
}
有没有更简洁的方式来写这个条件?
谢谢。
【问题讨论】:
-
您可以将条件分别放在 1 个函数/方法中...考虑单一职责和代码复杂性
-
在所有这些情况下,您似乎唯一想做的就是
perform_action_and_exit()- 因此,如果您按照 B001 的建议组织方法中的条件,您将能够执行类似的操作:if (shouldExit()) { perform_action_and_exit(); } -
这取决于你眼中什么是更干净的方式。我认为,它现在的构建方式只能抽象事物,因此您可以将这个验证编码在一个专门的对象中,这些对象链接在一起,可以返回下一个阶段、快捷阶段或空操作。例如,
GroupHandler.get(group)如果是G1,则返回StagedGroupHandler,否则为ShortcutHandler(只会返回动作执行阶段,不会进行任何验证)。然而,这只会简单地拆分子句并将其隐藏起来,而不是消除或普遍改进它。 -
level的允许值是多少? -
顺便说一下,
class不能是变量。
标签: java optimization coding-style