samedi 7 septembre 2019

IF statements with a common ELSE clause

I come across this problem quite a bit when I'm programming, where I need to use multiple if statements with a common else clause that triggers if none of the if statements trigger. There are a few ways I usually implement this behaviour:

Method 1 - Boolean Variable

triggered = False

if condition_1:
    // do stuff
    triggered = True

if condition_2:
    // do some different stuff
    triggered = True

if not triggered:
    // do the default stuff

Method 2 - Double Checking

if condition_1:
    // do stuff

if condition_2:
    // do some different stuff

if not (condition_1 || condition_2):
    // do the default stuff

Method 3 - Nested If Statements

if condition_1:
    // do stuff
    if condition_2:
        // do some different stuff
else if condition_2:
    //do some different stuff
else:
    // do the default stuff

All three methods are not ideal:
Method 1: requires an extra variable and some extra lines
Method 2: inefficient since you have to compute the conditions multiple times
Method 3: code is repetitive, and will get much more repetitive with more than two if statements

Is there a more concise/cleaner way to implement this behaviour (I'm more concerned about a general solution but if there are language specific solutions for python/java/c++ that would be neat as well)?

Aucun commentaire:

Enregistrer un commentaire