Sometimes you come accross duplicated code blocks that the only difference is having an additional condition to check if another condition is true. An Example of the Idea is given below.
From
if ( condition1 && condition2 ) {
//doSomething1
if ( conditionA || conditionB ) {
//doSomething2
}
} else if ( condition1 ) {
//doSomething1
if ( conditionA ) {
//doSomething2
}
}
In the above example, the only difference is if condition2 == true
then check for conditionB
To refactor it, we leave all execution rights to condition2
and conditionB
Assume:
condition1 = true
conditionA = false
with that, we get:
if ( true && condition2 ) {
//doSomething1
if ( false || conditionB ) {
//doSomething2
}
} else if ( true ) {
//doSomething1
if ( false ) {
//doSomething2
}
}
In the above example in the first
if
block, you will only executedoSomething2
, if and only ifcondition2
ANDconditionB
aretrue
.
So we can refactor it to the code below.
To
if ( condition1 ) {
//doSomething1
if ( conditionA || (condition2 && conditionB) ) {
//doSomething2
}
}
Codepen Example: https://codepen.io/jhynzar/pen/QRJpob?editors=0012
Top comments (0)