Going binary

Sometimes the if/else flow will not cut it: I go binary.

The problem

There are times when functions and methods will get flags and options coming from many places and handling those using if/else checks becomes a unelegant and unmaintainable chore:

function someFunction($option1 = true, $option2 = false, $option3 = true, $option4 = false)
{
    if($option1){
        if($option2 && $option3){
            ...
        } else if($option2 && !$option3 && $option4){
            ...
        }
    }

    ...and so on...
}

while slimming down the options or the function/method responsibilities might be the best way to do it I work with WordPress and often have to deal with legacy code that has stratified over time and what was a small responsibility function or method became a mess of related and interwoven options.

Bits

Binary system to the rescue a good way to go might be to convert all those boolean options into the base 2 mask everyone loves

function someFunction($option1 = true, $option2 = false, $option3 = true, $option4 = false)
{
    $options = 1 * $option1 + 2 * $option2 + 4 * $option3 + 8 * $option4;

    switch($options){
        case 0:
            // all false
            ....
            break;
        case 1:
            // just option1
            ....
            break;
        case 2:
            // just option2
            ....
            break;
        case 3:
            // option1 and option2
            ....
            break;
        case 5:
            // option1 and option3
            ....
            break;
        case ...:
    }
}

if not all the combinations are possible than the case entry needs not to be added to the switch loop. Further delegation and DRY code might make things even better.