mercredi 21 octobre 2015

Optimize if else condition with (repeatable actions in branches)

I have this code. At first jobDone is false and the program does the first step, then the second and sets the jobDone variable to true stating that all tasks completed successfully.

But I might choose to run this bit of code again and I don't want to do the first step again since it might not be necessary. So if the job has been done at least once and if checkSomething() concludes that everything is OK it should go ahead and do only secondStep();

Otherwise, if checkSomething() finds out that something is wrong then I must repeat the first and as well the second step (like in the initial situation).

jobDone = false;
if (jobDone) {
    if (checkSomething()) {
         doSecondStep();
    } else {
         doFirstStep();
         doSecondStep();
    }
} else {
    doFirstStep();
    doSecondStep();
    jobDone = true;
}

But I feel that i'm repeating myself. Is there a better way of writing this? Thank yoou.

Aucun commentaire:

Enregistrer un commentaire