2015-10-04 45 views
0

你会怎么写下面的代码冗余:消除,如果从环

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>在两个地方一样的,我怎么能消除冗余?

+1

它移动到一个单独的功能和呼叫那? –

回答

3

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

  • 码块:Condition1
  • 码块: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> 
} 
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> 
} 
1
if(Conditon 1){ 
      # code block 1... 

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

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