应该如何删除else块

时间:2017-05-22 06:20:51

标签: php laravel if-statement phpmd

PHPMD告诉我在这个测试中应该避免使用else阻止,但在这种情况下,我找不到删除它们的方法。

以下是代码:

if ($fight->c1 == NULL) {
    if ($fight->c2 == NULL) {
        // C1 and C2 Is Bye
        $this->assertEquals($parentFight->$toUpdate, NULL);
    }
    else {
        // C1 Is Bye
        $this->assertEquals($parentFight->$toUpdate, $fight->c2);
    }
}
else {
    if ($fight->c2 == NULL) {
        // C2 Is Bye
        $this->assertEquals($parentFight->$toUpdate, $fight->c1);
    }
    else {
        // C1 and C2 Are all set
        $this->assertEquals($parentFight->$toUpdate, NULL);
    }
}

任何想法???

7 个答案:

答案 0 :(得分:1)

还有另一种方法可以做到这一点:

if(($fight->c1 == null && $fight->c2 == null) || ($fight->c1 != null && $fight->c2 != null)) {
    // C1 and C2 Is Bye
    // C1 and C2 Are all set
    $this->assertEquals($parentFight->$toUpdate, null);
} else if($fight->c1 == null && $fight->c2 != null) {
    // C1 Is Bye
    $this->assertEquals($parentFight->$toUpdate, $fight->c2);
} else if($fight->c1 != null && $fight->c2 == null) {
    // C2 Is Bye
    $this->assertEquals($parentFight->$toUpdate, $fight->c1);
}

答案 1 :(得分:1)

也可以使用三元运算符完成,就像这样。

if (!$fight->c1) {
    $this->assertEquals($parentFight->$toUpdate, ($fight->c2 ?: null));
}

if (!$fight->c2) {
    $this->assertEquals($parentFight->$toUpdate, ($fight->c2 ?: null));
}

答案 2 :(得分:1)

$checkValue = null;
$cntNulls = (int)is_null($fight->c1) + (int)is_null($fight->c2);
if ($cntNulls === 1) {
    $checkValue = is_null($fight->c1) ? $fight->c2 : $fight->c1;
}

$this->assertEquals($parentFight->$toUpdate, $checkValue);

答案 3 :(得分:1)

似乎在$fight->c1不是null时,您希望传递$fight->c1。当$fight->c2不是null时,您想要传递$fight->c2。当两者都是null时,您想要传递null

你要做的是,

$param = null;
if($fight->c1 != null)
{
    $param = $fight->c1;
}
if($fight->c2 != null)
{
    $param = $fight->c2;
}

$this->assertEquals($parentFight->$toUpdate, $param);

但我会更进一步,抽象出$param解析过程,如

private function relolveParam($fight) {
    $param = null;
    if($fight->c1 != null)
    {
        $param = $fight->c1;
    }
    if($fight->c2 != null)
    {
        $param = $fight->c2;
    }
    return $param;
}

然后你最终只会,

$this->assertEquals($parentFight->$toUpdate, $this->relolveParam($fight));

答案 4 :(得分:0)

使用else if而非多个if...else

if ($fight->c1 == null && $fight->c2 == null) {
    // C1 and C2 Is Bye
    $this->assertEquals($parentFight->$toUpdate, null);
} else if($fight->c1 == null &&  $fight->c2 != null) {
    // C1 Is Bye
    $this->assertEquals($parentFight->$toUpdate, $fight->c2);
} else if($fight->c1 != null &&  $fight->c2 == null) {
    // C2 Is Bye
    $this->assertEquals($parentFight->$toUpdate, $fight->c1);
} else {
    // C1 and C2 Are all set
    $this->assertEquals($parentFight->$toUpdate, null);
}

答案 5 :(得分:0)

您可以使用两个if{}来代替if{}else{}

if(a){
  //do a
}else{
  //do !a
}

if(a){
  //do a
}
if(!a){
  //do !a
} 

答案 6 :(得分:0)

你也可以为你正在测试的每个案例进行一次测试,有4个明确的测试而不是一个测试,其中所有路径的测试都不明显

相关问题