tags:

views:

62

answers:

3

If I have a database table containing a flag that can have multiple states, should I do this

if ($Object->isStateOne()) {
  // do something
}
else if ($Object->isStateTwo()) {
  // do something else
}
else if ($Object->isStateThree()) {
  // do yet something else
}

or this

switch ($Object->getSomeFlag()) {
  case ObjectMapper::STATE_ONE:
    // do something
    break;

  case ObjectMapper::STATE_TWO:
    // do something else
    break;

  case ObjectMapper::STATE_THREE:
    // do yet something else
    break;
}

?

+2  A: 

Whichever makes sense, of course.

The switch looks much cleaner. But, what is this 'state' you are checking? If you're translating a string, use an array, for example.

The if has different behavior from switch. The method calls MAY have side effects. The if is better if multiple states may be active on the object at once, though.

strager
+1  A: 

The second option just seems to be the better solution. IMHO, the unsightly duplication of the comparison code that would accompany the methods of the first solution would be the show-stopper for me, for example:

public function isStateOne() {
  if(strcmp(ObjectMapper::STATE_ONE, '1') == 0) {
      return true;
  }
}
public function isStateTwo() {
  if(strcmp(ObjectMapper::STATE_TWO, '2') == 0) {
      return true;
  }
}
public function isStateThree() {
  if(strcmp(ObjectMapper::STATE_THREE, '3') == 0) {
      return true;
  }
}

Of course, others might disagree. I just don't like having classes cluttered up with 'almost the same' methods.

karim79
+1  A: 

From an OO perspective, both are discouraged. If you have different state, you may want to create a virtual methods, and override it in inherited class. Then based on polymorphism, you can avoid the if, and switch statement.

J.W.
At the expense of N more classes. And making it much harder to switch between states. Whether that makes senses depends on what the states are.
derobert
I don't think polymorphism will work, as this if/else / switch statement block has to go in UI code. What happens for each case won't be the same everywhere it is used.
Chad Johnson