Home > Mobile >  JS Avoid same if statement in multiple locations
JS Avoid same if statement in multiple locations

Time:10-07

I have a function that processes a large list of JSON Documents and inserts them into MongoDB.

I want to log what this function is doing at several locations and then chuck off the payload to S3. However, this is conditional from the callee.

function doStuffWithJSON(options={}) {
    const apiRes = getJSONFromAPI();

    if (options.logAndChuck) { console.log('we got results successfully') }

    //50 lines of code that are unconditionally being executed

    if (options.logAndChuck) { console.log('we did stuff with the result') }

    //Another 50 lines of code that are unconditionally being executed

    if (options.logAndChuck) { sendJsonToS3(apiRes) }
}

The repetitive pattern here is that I have the same if statement at multiple different locations of the function. Not sure if there is any way to avoid this just given the nature of it.

Was wondering if there was any pattern to clean stuff up like this.

Thanks!

CodePudding user response:

To put into code the suggestions in the comments of the question:

function doStuffWithJSON(options={}) {
    const apiRes = getJSONFromAPI();

    logAndChuck('we got results successfully')

    //50 lines of code that are unconditionally being executed

    logAndChuck('we did stuff with the result')

    //Another 50 lines of code that are unconditionally being executed

    if (options.logAndChuck) { sendJsonToS3(apiRes) }
}

function logAndChuck(options, message) {
    if (options.logAndChuck) { console.log(message) }
}

CodePudding user response:

It really depends - IMHO it's not a problem to have a simple if statement multiple times. However, if it's more complex, you could create a function for this - in local function scope or above taking a callback function:

function doStuffWithJSON(options={}) {
    const exec = (callbackFn) => {
        if (options.logAndChuck) {
            callbackFn();
        }
    };

    const apiRes = getJSONFromAPI();

    exec(() => console.log('we got results successfully'));

    //50 lines of code that are unconditionally being executed

    exec(() => console.log('we did stuff with the result'));

    //Another 50 lines of code that are unconditionally being executed

    exec(() => sendJsonToS3(apiRes));
}
  • Related