简体   繁体   中英

java:S1067 - Reduce the number of conditional operators (5) used in the expression (maximum allowed 3)

How can I reduce the number of conditional operators? Sonar showing Major issue like Reduce the number of conditional operators (5) used in the expression (maximum allowed 3) but those all condition mandatory to keep in this block:

private String processfromOrigin(Object value) {
    if ((value instanceof A) || (value instanceof B)
            || (value instanceof C) || (value instanceof D)
            || (value instanceof E)
            || (value instanceof F)) {
        return ((baseDto) processo).getProcess();
    } else if (value instanceof G) {
        return ((G) value ).getProcess();
    } else if (value instanceof H) {
        return ((H) value ).getProcess();
    } else {            
        return (String) value ;
    }
}

You can use code like below to simplify the first conditional in the if block:

import static java.util.Stream.of;
boolean checkABCDEF = of(A.class, B.class, C.class, D.class, E.class, F.class).
                      anyMatch(aClass -> aClass.isInstance(value))

of, you can encapsulate it in a local method:

    private boolean isABCDEF(Object x) {
        return Stream.of(A.class, B.class, C.class, D.class, E.class, F.class).
                      anyMatch(aClass -> aClass.isInstance(x));
    }

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