mercredi 29 juillet 2015

How to handle multiple exit points in Java

Sometimes I'm faced with a routine that will test some conditions and either continue or exit, something like the following code:

public void execute() {
    if (context.condition1()) {
        LOGGER.info("Condition 1 not satisfied.");
        return;
    }
    doSomeStuff();

    if (context.condition2()) {
        LOGGER.info("Condition 2 not satisfied.");
        return;
    }
    if (context.condition3()) {
        LOGGER.info("Condition 3 not satisfied.");
        return;
    }

    doRestOfStuff();
}

Let's assume there is no way to test these conditions before entrying this method. Maybe this is a servlet or a controller with this single entry point. From my experience (which is far from vast), this seems to be a common situation.

Now, this code doesn't smell good, does it? What would be the best strategy to handle this?

Aucun commentaire:

Enregistrer un commentaire