Rajat Saxena
Rajat Saxena

Reputation: 3935

Eliminate redundancy from if loop

how would you write the following code:

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

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

So here # <code block X> is same at two places, how can I eliminate the redundancy?

Upvotes: 0

Views: 45

Answers (3)

Peter Walser
Peter Walser

Reputation: 15706

General approach: find out the preconditions for each block to be executed:

  • code block 1: Condition1
  • code block 2: Condition1 && $device!=null
  • code block x: !Condition1 || !($device!=null)

The precondition for block 2 is the opposite of the precondition for block x: !(a && b) = !a || !b, so they're suited to go into an if-else:

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

Upvotes: 3

songyuanyao
songyuanyao

Reputation: 173044

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

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

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

Upvotes: 1

CoderNeji
CoderNeji

Reputation: 2074

//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>
}

Upvotes: 0

Related Questions