如何使复杂的条件看起来不错并节省语句数? [英] How to make complex conditions look nice and save the number of statements?

查看:70
本文介绍了如何使复杂的条件看起来不错并节省语句数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java应用程序中,我有很多条件只能决定一个动作。我的问题是如何使其看起来更好(我使用NetBeans,所以我希望解决方案不会被其代码格式化功能破坏)。我还希望那里的if / else语句数量尽可能少,因为我认为它将使它更快。

In my java application I have a huge set of conditions which decides just one action. My question is how to make it look nice (I use NetBeans so I'd prefer solution that will not be broken by its code formatting function). I'd also like to have there as low amount of if/else statements as possible, because I think it will make it faster.

我的原始代码是一团糟,所以我制作了一个动作图:。 要复制,如果您想玩的话。请记住,该图对于UML 语法并不完美,部分原因是我是使用Google文档制作的。

My original code was a mess, so I made an action diagram:. Take a copy if you want to play with it. Please keep in mind that the diagram is not perfect as to UML syntax, partly because I made it using google docs.

这是代码:

if (!config.get("checkForSpecials") || event.isNotSpecial()) {
    if (config.get("filterMode").equals("blacklist")) {
        if (!itemFilter.contains(event.getItem().getName())) {
            item.process();
        }
    } else if (config.get("filterMode").equals("whitelist")) {
        if (itemFilter.contains(event.getItem().getName())) {
            item.process();
        }
    } else {
        item.process();
    }
}

有两件事我不喜欢-条件不太清楚(尤其是当我展开完整的方法名称和配置字符串时),并且存在过程方法调用存在3次这一事实。

There are two things I don't like about it - the conditions are not too clear (especially when I unfold full method names and config strings), and the fact that the process method call is there three times.

推荐答案

从函数中提取布尔值并缓存返回值可以帮助澄清代码。

Factoring booleans out and caching return values from method calls can help clarify code.

此外,在逻辑表上绘制所有结果可以帮帮我。我使用此工具来提供帮助。

In addition, plotting all the outcomes on a logic table can help. I use this tool to help.

使用链接的工具:

A: config.get("filterMode").equals("blacklist")
B: config.get("filterMode").equals("whitelist")
C: filterContainsName (see below)

该工具会淘汰:

(!A && !B) || (!A && C) || (A && !C)

这会导致下面的代码(稍有调整将(!A&& C)替换为(B&& C)):

Which leads to the code below (with a small tweak that replaces (!A && C) with (B && C)):

boolean filterContainsName = itemFilter.contains(event.getItem().getName());
boolean useBlacklist       = config.get("filterMode").equals("blacklist");
boolean useWhitelist       = config.get("filterMode").equals("whitelist");

if (!config.get("safeMode") || event.isSafe()) {
    if((!useBlackList && !useWhiteList) ||
       ( useWhiteList &&  filterContainsName) ||
       ( useBlackList && !filterContainsName)) {
        item.process();
    }
}

这篇关于如何使复杂的条件看起来不错并节省语句数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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