mercredi 10 mars 2021

Is there a better coding pattern to execute either of these PHP examples?

Sometimes I end up reading or writing deeply nested if statements in PHP. Here is an example of the original pattern:

$keepGoing = FALSE;
$valid = TRUE;
if($valid) {
    $otherstuff = TRUE;
    if($valid) {
        $goodstuff();
        echo 'working';
        $valid = FALSE;
        $keepGoing = TRUE;
        if($valid) {
            echo 'never gets called';
        }
    }
}
if($keepGoing) {
}

I started thinking about a better way to write it, and came up with this:

do {
    $valid = TRUE;
    
    if(!$valid) {
        // log reason
        break;
    }

    $otherstuff = TRUE;

    if(!$valid) {
        // log reason
        break;
    }

    $goodstuff();
    echo 'working';
    $valid = FALSE;

    if(!$valid) {
        // log reason
        break;
    }

    echo 'never gets called';

    if(!$valid) {
        // log reason
        break;
    }

} while(FALSE);

Using a do/while loop like that is kind of strange, I know. I'm wondering if there is some sort of coding pattern that I don't know that avoids nested if statements. Another example of what I am looking for (that is not valid code) would be this:

if($thisBoolean) {
    if($otherBoolean) {
        endif 2;
    }
    echo "never gets called";
}

Please don't give me architectural answers like abstraction, modules, includes. I'm looking for a pattern when you really want to write a code block that has nested if statements. Sorry to be picky!

Aucun commentaire:

Enregistrer un commentaire