Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewriting a conditional statement in Java

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();
}
like image 492
newguy Avatar asked Jul 27 '10 01:07

newguy


People also ask

How do you refactor an if statement?

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.


2 Answers

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.

like image 140
Nils Pipenbrinck Avatar answered Oct 11 '22 01:10

Nils Pipenbrinck


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.

like image 35
Joel Avatar answered Oct 10 '22 23:10

Joel