samedi 17 juin 2017

Simplifying seemingly redundant if-else statement

I have the following if-else statement:

if (entry.getContent() != newContent) {
    entry.setContent(newContent);
    if (!entry.isActive()) {
        entry.setActive(true);
    }
    update(entry);
} else if (!entry.isActive()) {
    entry.setActive(true);
    update(entry);
}

I feel like this is somewhat redundant, because this same code is called in both the if and the else if blocks:

if(!entry.isActive()) {
    entry.setActive(true);
}
update(entry);

Two solutions came to my mind to simplify the statement.

The first one, to move the redundant code outside the statement:

if (entry.getContent() != newContent) {
    entry.setContent(newContent);
}
if(!entry.isActive()) {
    entry.setActive(true);
}
update(entry);

The problem with this is the code will run every single time, even if none of the original conditions are true.

The second one is to merge the conditions with the OR operator:

if ((entry.getContent() != newContent) || !entry.isActive()) {
    entry.setContent(newContent);
    entry.setActive(true);
    update(entry);
}

This is also a bad solution, since unnecessary code will be called.

Can the original statement be further simplified? I'd really appreciate any advice.

Aucun commentaire:

Enregistrer un commentaire