samedi 6 août 2016

two-dimensional if/then matrix

I have to take action based on two variables ($x and $y). The following meets those needs, but is not very readable, and it is not really obvious that $x/$y of 1/4 does the same thing as $x/$y of 5/3. From a readability and maintainability perspective, what is the best way to code this? While I am specifically asking for a PHP solution, hopefully the solution could be extended to other languages such as JavaScript.

<?php
  switch($x) {
      case 1: case 2: case 3:
      switch($y) {
          case 1: case 2:
          doTask(1);
          break;
          case 3: case 4:
          doTask(2);
          break;
          default:
          doTask(3);
      }
      break;
      case 4: case 5:
      switch($y) {
          case 1: case 2: case 4:
          doTask(4);
          break;
          case 3:
          doTask(2);
          break;
          default:
          doTask(2);
      }
      break;
      default:
      switch($y) {
          case 1:
          doTask(6);
          break;
          case 2: case 3: case 4:
          doTask(2);
          break;
          default:
          doTask(3);
      }
  }
?>

Aucun commentaire:

Enregistrer un commentaire