lundi 7 novembre 2016

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

Aucun commentaire:

Enregistrer un commentaire