从if循环中消除冗余

时间:2015-10-04 14:38:21

标签: design-patterns

您将如何编写以下代码:

if(Conditon 1){
            # code block 1...

            // another if condition
            if($device!=null){
                # code block 2...
            }else{
                # <code block X>
            }
}else{
            # <code block X>
}

所以这里# <code block X>在两个地方是一样的,我怎样才能消除冗余呢?

3 个答案:

答案 0 :(得分:3)

一般方法:找出每个要执行的块的前提条件:

  • 代码块 1 Condition1
  • 代码块 2 Condition1 && $device!=null
  • 代码块 x !Condition1 || !($device!=null)

块2的前提条件与块x:!(a && b) = !a || !b的前提条件相反,因此它们适合进入if-else

if(Conditon1){
    # code block 1...
}
if(Conditon1 && $device!=null){
    # code block 2...
} else {
    # <code block X>
}

答案 1 :(得分:1)

if(Conditon 1){
            # code block 1...

            // another if condition
            if($device!=null){
                # code block 2...
            }
}

if (!Condition1 || $device==null){
    # <code block X>
}

答案 2 :(得分:0)

//A variable to store true/false
var a = true;
if(Conditon 1){
  # code block 1...    
  // another if condition
    if($device!=null){
     # code block 2...
   a =false;
   }
}
 if(a){
 # <code block X>
}
相关问题