Reputation: 3935
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
Reputation: 15706
General approach: find out the preconditions for each block to be executed:
Condition1
Condition1 && $device!=null
!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
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
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