Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplify huge if statements - design pattern?

Tags:

php

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?

like image 274
longneck Avatar asked Feb 10 '11 19:02

longneck


1 Answers

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.

like image 182
ircmaxell Avatar answered Oct 13 '22 19:10

ircmaxell