Rewriting conditional statements in Java
Suppose I have the following code, which basically determines some condition matches, then assigns Boolean values, and then runs some code If the Boolean value is false, an exception is thrown What if the Boolean value is false without running the rest of the code, and I want it to throw an exception immediately? If I just put the second conditional statement into the first conditional statement, there will be duplicate code Please tell me a clever way (I have modified the code to look like my actual code)
boolean booleanValue = false; Permission value; if (someCondition) { value = getPermission_1(); booleanValue = someMethod(value); useValue_1(value); } else { value = getPermission_2(); booleanValue = anotherMethod(value); useValue_2(value); } if (!booleanValue) { throw Exception(); }
Solution
How to eliminate Boolean variables? You can rewrite the code like this:
if (someCondition) { if (!someMethod()) { throw new Exception(); } some codes... } else { if (!anotherMethod()) { throw new Exception(); } some codes... }
It seems easier for me, but such a thing is a matter of taste
Extra advantage: if the exception ends with a stack trace, you know what the condition is because you have two different throw statements This may speed up debugging