dimanche 19 février 2017

Clearer nested if statements

This might be a question for Code Review, but I've not used that yet, so indulge me:

Before a Photoshop script there are a number of checks than need to be done. However, this tends to result in a bird's nest of if statements which can be confusing to cold debug later. It looks a bit ugly especially if extra conditions get piled on afterwards.

Been wracking my brain for an alternative:

if (we_can_do_it) {
    // main
}

function we_can_do_it(condition1, condition2, condition3) {
    var errorString = "";
    // if it's all true we are good to go
    if (condition1 && condition2 && condition3) return true;
    if (condition1 == null) errorString += "Missing McGuffin";
    if (condition1 == false) errorString += "Condition1 is off";
    if (condition1 == undefined) errorString += "Gone badly wrong";
    return errorString;
}

Is there a there another way that I can (Switch??):
- make sure all conditions are true to start main
- set error messages back to show why main hasn't started.

Aucun commentaire:

Enregistrer un commentaire