Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many if-else statement, any way to refactor it

Can this be refactored? or this looks fine. (variable names changed)

if (cmpScope.equals(GLOBAL)) {
            return true;
        } else if ((cmpScope.equals(X) || cmpScope.equals(Y))
                && cid == pid) {
            return true;
        } else if (cmpScope.equals(Z) && cid != pId) {
            return true;
        } else if (cmpScope.equals(V) && cid == pid) {
            return true;
        } else if (cmpScope.equals(Z) && cid == pid && cSubId != pSubId) {
            return true;
        }
        return false;
like image 961
dejavu Avatar asked Nov 13 '15 09:11

dejavu


People also ask

How do you refactor too many if-else?

Just combine all expressions with or-operators, since they all return true. Save this answer.

What can be used instead of if-else?

The Ternary Operator One of my favourite alternatives to if...else is the ternary operator. Here expressionIfTrue will be evaluated if condition evaluates to true ; otherwise expressionIfFalse will be evaluated. The beauty of ternary operators is they can be used on the right-hand side of an assignment.


2 Answers

Just combine all expressions with or-operators, since they all return true.

return  ((cmpScope.equals(GLOBAL) ||
         ((cmpScope.equals(X) || cmpScope.equals(Y)) && cid == pid) ||
         (cmpScope.equals(Z) && cid != pId) ||
         (cmpScope.equals(V) && cid == pid) ||
         (cmpScope.equals(Z) && cid == pid && cSubId != pSubId));
like image 129
Michel Keijzers Avatar answered Oct 27 '22 03:10

Michel Keijzers


You could store the result of the conditions in variables and handle all conditions in one statement. (Though I don't think that's a better solution in all cases)

boolean trueCond1 = cmpScope.equals(GLOBAL);
boolean trueCond2 = (cmpScope.equals(X) || cmpScope.equals(Y)) && cid == pid;
boolean trueCond3 = cmpScope.equals(Z) && cid != pId;
boolean trueCond4 = cmpScope.equals(V) && cid == pid;
boolean trueCond5 = cmpScope.equals(Z) && cid == pid && cSubId != pSubId;

return (trueCond1 || trueCond2 || trueCond3 || trueCond4 || trueCond5);
like image 38
R.G. Avatar answered Oct 27 '22 03:10

R.G.