![](/img/trans.png)
[英]java:S1067 - Reduce the number of conditional operators (5) used in the expression (maximum allowed 3)
[英]java Expression too complex reduce the number of conditionl operators
我们有一个针对我们的代码运行的程序,以遵守一些编码标准。
该计划说:
表达式不应该太复杂,减少使用的条件运算符的数量,他的表达式Min允许3。
如何减少条件运算符的数量? 也许把关键事件放在一个数组中?
public boolean onlyNumbers(KeyEvent evt) {
char c = evt.getKeyChar();
boolean returnValue = true;
if (
!(
Character.isDigit(c)
|| c == KeyEvent.VK_BACK_SPACE
|| c == KeyEvent.VK_DELETE
|| c == KeyEvent.VK_END
|| c == KeyEvent.VK_HOME
)
|| c == KeyEvent.VK_PAGE_UP
|| c == KeyEvent.VK_PAGE_DOWN
|| c == KeyEvent.VK_INSERT
) {
evt.consume();
returnValue = false;
}
return returnValue;
}
final String junkChars = new String(new char[] {
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_DELETE,
KeyEvent.VK_END,
KeyEvent.VK_HOME
/* The last three seem unused in the latest version
KeyEvent.VK_PAGE_UP,
KeyEvent.VK_PAGE_DOWN,
KeyEvent.VK_INSERT */
});
if(!Character.isDigit(c) && junkChars.indexOf(c) == -1) {
evt.consume();
return false;
} else {
return true;
}
您的样本的严格重构看起来像:
public boolean onlyNumbers(KeyEvent evt) {
char c = evt.getKeyChar();
boolean returnValue = true;
boolean bad = Character.isDigit(c);
bad |= (c == KeyEvent.VK_BACK_SPACE);
bad |= (c == KeyEvent.VK_DELETE);
bad |= (c == KeyEvent.VK_END);
bad |= (c == KeyEvent.VK_HOME);
boolean good = (c == KeyEvent.VK_PAGE_UP);
good |= c == KeyEvent.VK_PAGE_DOWN;
good |= c == KeyEvent.VK_INSERT;
if (!bad || good) {
evt.consume();
returnValue = false;
}
return returnValue;
}
这突出了其他人关于放置支架的注意事项
你可以这样做的一种方法是构造一个包含你要测试的所有字符的HashSet<Character> keys
,然后使用keys.contains(c)
来测试它是否是其中之一。
或者,您可以使用switch
语句,并让所有这些字符落入同一代码块。
但我个人最喜欢的是忽略警告。 代码非常清晰(模数ajb关于括号的注释)。
这是一种方法。 可以通过使用数组来改进。
public boolean onlyNumbers(KeyEvent evt) {
char c = evt.getKeyChar();
boolean returnValue;
returnValue = !(Character.isDigit(c));
returnValue &= !(c == KeyEvent.VK_BACK_SPACE);
returnValue &= !(c == KeyEvent.VK_DELETE);
returnValue &= !(c == KeyEvent.VK_END);
returnValue &= !(c == KeyEvent.VK_HOME);
returnValue |= (c == KeyEvent.VK_PAGE_UP);
returnValue |= (c == KeyEvent.VK_PAGE_DOWN);
returnValue |= (c == KeyEvent.VK_INSERT);
if(returnValue)
{
evt.consume();
returnValue = !returnValue;
}
return returnValue;
}
前五个和后三个任务可以在各自的分组中压缩到两个总分配,但这将归结为您的编码标准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.