philosopher
philosopher

Reputation: 1151

How can I refactor this code to remove duplication?

In the interest of DRY (Don't Repeat Yourself) code, I am wondering if the code given below can be refactored in any way. In the below code, as you can see I am repeating the statements for assignments for both condition1 and condition2 since at the end of each of the if statements I make a different function call.

websocket.onmessage = async(event) => {
    const data = JSON.parse(data)
    let infoFromExternalApi1, infoFromExternalApi2, infoFromExternalApi3

    // Assignments for infoFromExternalApi variables are repeated due to difference in function calls doSomething() and doSomethingElse()
    if (condition1) {
        infoFromExternalApi1 = await getInfoFromExternalApi1()
        infoFromExternalApi2 = await getInfoFromExternalApi2()
        infoFromExternalApi3 = await getInfoFromExternalApi3()

        doSomething()
    }

    if (condition2) {
        infoFromExternalApi1 = await getInfoFromExternalApi1()
        infoFromExternalApi2 = await getInfoFromExternalApi2()
        infoFromExternalApi3 = await getInfoFromExternalApi3()

        doSomethingElse()
    }
}

Upvotes: 0

Views: 43

Answers (1)

Bergi
Bergi

Reputation: 664356

You're probably looking for

websocket.onmessage = async(event) => {
    const data = JSON.parse(data)
    let infoFromExternalApi1, infoFromExternalApi2, infoFromExternalApi3

    if (condition1 || condition2) {
        infoFromExternalApi1 = await getInfoFromExternalApi1()
        infoFromExternalApi2 = await getInfoFromExternalApi2()
        infoFromExternalApi3 = await getInfoFromExternalApi3()
    }
    if (condition1) {
        doSomething()
    }
    if (condition2) {
        doSomethingElse()
    }
}

Of course this works differently than your original code if both conditions are true, namely fetching the info from the external apis only once.

Upvotes: 1

Related Questions