DEV Community

Mj Tapiru
Mj Tapiru

Posted on

4 1

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay