mercredi 9 juin 2021

Avoid continuous "if (...)" checks while executing function

I have a function which looks like the following:

public Status execute() {
    
    Status status = doSomething();

    if (status != Status.ABORTED) {
        status = doSomethingElse();
    }

    if (status != Status.ABORTED) {
        status = doAgainSomethingElse(param1, param2);
    }

    if (status != Status.ABORTED) {
        doSomethingWhichDoesntReturn(param3);
    }

    //etc.
    
    return status;
}

So basically this function needs to return a Status. This is computed by a first function, and then recomputed by successive functions at the condition that, when those functions are executed, status != Status.ABORTED.

I would like to refactor this code but I don't have any valid idea in my mind.

If it was always status = someFunction(someParam), I would have used a list of Function<TypeInput, Status> and executed that list in loop:

List<Function<TypeInput, Status>> actions = List.of(function1, function2...);
for (Function<TypeInput, Status> f : actions) {
    if (status != Status.ABORTED) {
        status = f.apply(input);
    }
}

The problem though is that each action may be different (sometimes it's a function which returns Status, sometimes there are parameters but not always the same size, sometimes it's just a void function etc.)

Does anyone have any idea?

Note: as soon as the status gets Status.ABORTED, I can return (I don't need to execute the rest of the function as anything is executed only if the status is not Status.ABORTED).

Aucun commentaire:

Enregistrer un commentaire