Hatefiend Hatefiend - 1 month ago 8
Java Question

Java - 'Finally' equivalent for if statement

EDIT: I only want the

finally
code to be executed if one of the
if
or
else if
statements were true.

Many many times, I run into the following situation:

if (condition1)
do stuff
do something
else if (conditon2)
do other stuff
do something
else if (condition3)
algorithm here
do something


If there were a
finally
clause on if statements, I could reduce that into:

if (condition1)
do stuff
else if (conditon2)
do other stuff
else if (condition3)
algorithm here
finally
do something


I'm trying to find some solution where
do something
only needs to be called once, without making an additional method, doing some weird out of place if statement, or making a flag like:

boolean special = false;

if (condition1)
do stuff
special = true;
else if (conditon2)
do other stuff
special = true;
else if (condition3)
algorithm here
special = true;

if (special) // <--- bad solution, doesn't simplify anything
do something

Answer

Although there is no special construct to do what you want to do, you can rewrite the last attempt with a single assignment in the final else branch:

boolean doFinally = true;
if (condition1)
    do stuff
else if (conditon2)
    do other stuff
else if (condition3)
    algorithm here
else
    doFinally = false;

if (doFinally)
    do something

This does simplify your code, because the repetition of setting special to true is now gone.