DEV Community 👩‍💻👨‍💻

Mj Tapiru
Mj Tapiru

Posted on

Code Duplication Refactoring on Conditional Conditions

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 execute doSomething2, if and only if condition2 AND conditionB are true.
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)

All DEV content is created by the community!

Hey, if you're landing here for the first time, you should know that this website is a global community of folks who blog about their experiences to help folks like you out.

Sign up now if you're curious. It's free!