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();
}
So, how do you refactor multiple nested if statements? The easiest possible way is to use guard clauses. A guard clause is an if statement that checks for a condition and favors early exit from the current method. If the condition is satisfied, the if block returns from the method.
How about eliminating the boolean variable? You could rewrite your code like this:
if (someCondition) {
if (!someMethod()) {
throw new Exception();
}
some codes...
}
else {
if (!anotherMethod()) {
throw new Exception();
}
some codes...
}
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.
Instead of
booleanValue = anotherMethod();
you would simply write
if( !someMethod() )
throw new SomeException();
On throwing a generic Exception -- don't. The reason that you're throwing an exception is to tell the caller that something exceptional occurred. It is almost always useful to tell them what, otherwise neither the caller nor you can do anything about it.
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