Say if I have the code below, it’s bascially determining some condition is matched and then assign the boolean value, then run some codes. Then throw an exception if the booleanValue is false. What if I want it to throw an exception immediately if the booleanValue is false without running the rest of the codes? If I just put the second conditional statement into the first one there will be duplicated codes. Please show me a smart way to do this (I’ve modified the code to be looked like my actual codes).
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();
}
How about eliminating the boolean variable? You could rewrite your code like this:
That looks easier to my eyes, but such things are a matter of taste…
Extra advantage: If the exception ends up in a stack-trace you know what the condition was because you have two different throw-statements. That may speed up the debugging a bit.