5

Do I have to get rid of continuous declarations

 2 years ago
source link: https://www.codesd.com/item/do-i-have-to-get-rid-of-continuous-declarations.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Do I have to get rid of continuous declarations

advertisements

I've read in this Q&A that using continue statements in loops should be generally avoided. Is the rule worth sticking to for the code below? If yes, what would be the best way to refactor it to get rid of them?

    for (property in formInput) {
        if (!formInput.hasOwnProperty(property) || property === "Id") {
            continue;
        }
        if (property.slice(-3) === "_Id") {
            setMagicSuggestFromFormInput(property);
            continue;
        }
        if (property.slice(-3) === "_bl" && formInput[property] === true) {
            $("#" + property).prop("checked", true);
            continue;
        }
        $("#" + property).val(formInput[property]);
    }

Edit: If you think the loop has to be refactored, besides indicating on how it can be done, could you please tell me why you consider the proposed refactoring a better design choice?


Your code:

for (property in formInput) {
    if (!formInput.hasOwnProperty(property) || property === "Id") {
        continue;
    }
    if (property.slice(-3) === "_Id") {
        setMagicSuggestFromFormInput(property);
        continue;
    }
    if (property.slice(-3) === "_bl" && formInput[property] === true) {
        $("#" + property).prop("checked", true);
        continue;
    }
    $("#" + property).val(formInput[property]);
}

Is the equivalent of:

for (property in formInput) {
    if (property.slice(-3) === "_Id") {
        setMagicSuggestFromFormInput(property);
    } else if (property.slice(-3) === "_bl" && formInput[property] === true) {
        $("#" + property).prop("checked", true);
    } else if (formInput.hasOwnProperty(property) && property !== "Id") {
        $("#" + property).val(formInput[property]);
    }
}

Which would be the preferred method as it's properly utilizing if/then/else and is easier to reason with logically.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK