简体   繁体   中英

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

With what changes sonar will be happy from below code

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)

You could encapsulate all error codes into a dedicated 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM