![](/img/trans.png)
[英]How to fix sonar issues for Reduce the number of conditional operators (5) used in the expression (maximum allowed 3) in java
[英]Reduce the number of conditional operators (4) used in the expression (maximum allowed 3) in SONAR
從下面的代碼聲納顯示主要問題,例如減少表達式中使用的條件運算符 (4) 的數量(最多允許 3 個) ,但所有條件都必須保留在此塊中
從下面的代碼中聲納會有什么變化
if (cartResJsonObj.getString(AccessIdConstants.APP_STATUS_MSG).equalsIgnoreCase("INVALID_REQUEST")
|| cartResJsonObj.getString(AccessIdConstants.APP_STATUS_MSG).equalsIgnoreCase("ERR_EMPTY")
|| cartResJsonObj.getString(AccessIdConstants.APP_STATUS_MSG).equalsIgnoreCase("ERR_INVALID_DATA")
|| cartResJsonObj.getString(AccessIdConstants.APP_STATUS_MSG).equalsIgnoreCase("ERR_SIM_DATE_MISSING")
|| cartResJsonObj.getString(AccessIdConstants.APP_STATUS_MSG).equalsIgnoreCase("ERR_SIM_NOT_YET_ELIGIBLE")) {
errorMessage = ErrorMessages.EPO_VALIDATEOTP_ERR_04;
detailsMessage = ErrorConstants.INVALID_REQUEST;
}
檢查字符串,大寫,針對一些集合,例如
Arrays.asList("INVALID_REQUEST", "ERR_EMPTY")
.contains(cartResJsonObj.getString(AccessIdConstants.APP_STATUS_MSG).toUpperCase())
(集合可以存儲在一個 static 最終變量中,而不是每次都構建)
您可以將所有錯誤代碼封裝到一個專用的enum
中。 這也將有助於減少魔術字符串的使用(類似於魔術數字),因為枚舉可以安全地在其他地方使用,而不是復制字符串。
private enum ErrorStatus {
INVALID_REQUEST,
ERR_EMPTY,
ERR_INVALID_DATA,
ERR_SIM_DATE_MISSING,
ERR_SIM_NOT_YET_ELIGIBLE;
//-----------------------------------------------------------------------
private static final Map<String, ErrorStatus> ERROR_CODES;
static {
Map<String, ErrorStatus> codes = new HashMap<>();
for (ErrorStatus value : values()) {
codes.put(value.toString(), value);
}
ERROR_CODES = Collections.unmodifiableMap(codes);
}
public static ErrorStatus from(String value) {
return ERROR_CODES.get(value.toUpperCase());
}
public static boolean matches(String value) {
return from(value) != null;
}
}
然后可以將您的原始調用簡化為:
// no need to call #getString multiple times like in your example
String status = cartResJsonObj.getString(AccessIdConstants.APP_STATUS_MSG);
if (ErrorStatus.matches(status)) {
errorMessage = ErrorMessages.EPO_VALIDATEOTP_ERR_04;
detailsMessage = ErrorConstants.INVALID_REQUEST;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.