重构if语句包含很多或

时间:2018-09-27 20:39:32

标签: php if-statement refactoring

如何重构此条件以使其更简单,更清洁?每个逻辑都完全不同。

if(in_array($sides, [self::ALL_SIDES, self::HORIZONTAL_SIDES, self::TOP_SIDE])) {
    //do a()
}

if(in_array($sides, [self::ALL_SIDES, self::HORIZONTAL_SIDES, self::BOTTOM_SIDE])) {
    //do b()
}

if(in_array($sides, [self::ALL_SIDES, self::VERTICAL_SIDES, self::LEFT_SIDE])) {
    //do c()
}

if(in_array($sides, [self::ALL_SIDES, self::VERTICAL_SIDES, self::RIGHT_SIDE ])) {
    //do d()
}

4 个答案:

答案 0 :(得分:0)

尝试一下

$dos =($sides === self::TOP_SIDE)        ? ['a'] : (
      ($sides === self::BOTTOM_SIDE)     ?     ['b'] : (
      ($sides === self::LEFT_SIDE)       ?         ['c'] : (
      ($sides === self::RIGHT_SIDE)      ?             ['d'] : (
      ($sides === self::HORIZONTAL_SIDES)? ['a','b'] : (
      ($sides === self::VERTICAL_SIDES)  ?         ['c','d'] : (
      ($sides === self::ALL_SIDES)       ? ['a','b','c','d']))))));

foreach($dos as $do) $do();

答案 1 :(得分:0)

恕我直言,这是嵌套if更具可读性的场合之一。这只是这种情况的一种方法,可能不是最适合其他情况的方法。

if ($sides==self::ALL_SIDES) {
    // do stuff, that (nearly) always should apply

    if ($sides==self::HORIZONATAL_SIDES) {
          // do stuff that applies to all horizontal sides
          if ($sides==self::TOP_SIDE) {
               // do top-stuff
          } elseif ($sides==self::BOTTOM_SIDE)  {
               // do other stuff
          }
    }
    // copy & adjust the same for vertical...
} else {
   // oops, an error!
}

答案 2 :(得分:0)

如果逻辑总是调用函数,则可以创建一个关联数组,将每个不同的值映射到相应的函数。

$vertical_side_map = [
    self::LEFT_SIDE => 'c',
    self::RIGHT_SIDE => 'd'
];

foreach ($vertical_side_map as $key => $func) {
    if(in_array($sides, [self::ALL_SIDES, self::VERTICAL_SIDES, $key])) {
        $func();
    }
}


$horizontal_side_map = [
    self::TOP_SIDE => 'a',
    self::BOTTOM_SIDE => 'b',
];

foreach ($horizontal_side_map as $key => $func) {
    if(in_array($sides, [self::ALL_SIDES, self::HORIZONTAL_SIDES, $key])) {
        $func();
    }
}

答案 3 :(得分:0)

np.random.seed(123) # for reproducibility

np.random.choice(range(10), replace=False, size=4)
# array([4, 0, 7, 5])

PhpFiddle