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;
Just combine all expressions with or-operators, since they all return true. Save this answer.
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.
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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With