简体   繁体   中英

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()
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM