i potentially have a set of if statements that look like this:
if (a and b and c and d) {
  // do stuff
} else (!a and b and c and d) {
  // do something else
} else (!a and !b and c and D) {
  // do yet something else
} ...
and so on for all possible permutations.
i thought of doing this:
switch ((a ? 'Y' : 'N') . (b ? 'Y' : 'N') . (c ? 'Y' : 'N') . (d ? 'Y' : 'N')) {
  case 'YNYN':
    // do stuff
    break;
  case 'NNNN':
    // etc.
    break;
}
is there a better way?
What I would likely do (without knowing the specifics) is build a series of classes for each state. Then push the doStuff onto that class:
class DoStuff { //The Client
    protected $strategies = array();
    public function addStrategy(iDoStuffStrategy $strategy) {
        $this->strategies[] = $strategy;
    }
    public function doStuff ($a, $b, $c, $d) {
        foreach ($this->strategies as $strategy) {
            if ($strategy->test($a, $b, $c, $d)) {
                return $strategy->doStuff();
            }
        }
        throw new RuntimeException('Unhandleable Situation!');
    }
}
interface iDoStuffStrategy {
    // Return a bool if you can handle this situation
    public function test($a, $b, $c, $d);
    // Execute the implementation
    public function doStuff();
}
Then, each class would look like this:
public function StrategyFoo implements iDoStuffStrategy {
    public function test($a, $b, $c, $d) {
        return $a && $b && $c && $d;
    }
    public function doStuff() {
        //DoStuff!
    }
}
public function StrategyBar implements iDoStuffStrategy {
    public function test($a, $b, $c, $d) {
        return !$a && $b && $c && $d;
    }
    public function doStuff() {
        //DoStuff!
    }
}
It's basically an implementation of the Strategy Pattern. Doing it that way allows you to separate out the decision tree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With