[英]Reduce the number of conditional operators (4) used in the expression (maximum allowed 3) in SONAR
From below piece of code sonar showing Major issue like Reduce the number of conditional operators (4) used in the expression (maximum allowed 3) but those all condition mandatory to keep in this block从下面的代码声纳显示主要问题,例如减少表达式中使用的条件运算符 (4) 的数量(最多允许 3 个) ,但所有条件都必须保留在此块中
With what changes sonar will be happy from below code从下面的代码中声纳会有什么变化
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;
}
Check the string, uppercased, against some collection, eg检查字符串,大写,针对一些集合,例如
Arrays.asList("INVALID_REQUEST", "ERR_EMPTY")
.contains(cartResJsonObj.getString(AccessIdConstants.APP_STATUS_MSG).toUpperCase())
(The collection can be stored in a static final variable, rather than building each time) (集合可以存储在一个 static 最终变量中,而不是每次都构建)
You could encapsulate all error codes into a dedicated enum
.您可以将所有错误代码封装到一个专用的
enum
中。 This would also help to reduce the usage of magic strings (analog to magic numbers ), since the enum can safely be used elsewhere instead of copying the strings.这也将有助于减少魔术字符串的使用(类似于魔术数字),因为枚举可以安全地在其他地方使用,而不是复制字符串。
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;
}
}
Your original call can then be simplified to:然后可以将您的原始调用简化为:
// 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.