我有以下代码:
Pattern p1 = Pattern.compile("foo1");
Pattern p2 = Pattern.compile("foo2");
Pattern p3 = Pattern.compile("foo3");
Pattern p4 = Pattern.compile("foo4");
Pattern p5 = Pattern.compile("foo5");
if (p1.matcher(kvTarif.getkey()).matches() || p2.matcher(getkey()).matches() ||
p3.matcher(getkey()).matches() || p4.matcher(getkey()).matches() ||
p5.matcher(getkey()).matches())
checkstyle表示布尔复杂度为4(最大允许为3)。
如何降低复杂性?
您可以根据要匹配的逻辑将模式的数量减少到2个:
Pattern p1 = Pattern.compile("foo1");
Pattern p2 = Pattern.compile("foo2|foo3|foo4|foo5"); // match foo2 through foo5
if (p1.matcher(kvTarif.getkey()).matches() || p2.matcher(getkey()).matches()) {
// handle this case
}
正如用户@JonnyHenly提到的,您可以使用以下命令进一步简化第二个模式:
Pattern p2 = Pattern.compile("foo[2-5]");