![](/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.