Clean Code – How to Edit a Chain of If-Else Statements to Adhere to Uncle Bob’s Clean Code Principles?

clean codeconditions

I'm trying to follow Uncle Bob's clean code suggestions and specifically to keep methods short.

I find myself unable to shorten this logic though:

if (checkCondition()) {addAlert(1);}
else if (checkCondition2()) {addAlert(2);}
else if (checkCondition3()) {addAlert(3);}
else if (checkCondition4()) {addAlert(4);}

I cannot remove the elses and thus separate the whole thing into smaller bits, cause the "else" in the "else if" helps performance – evaluating those conditions is expensive and if I can avoid evaluating the conditions below, cause one of the first ones is true, I want to avoid them.

Even semantically speaking, evaluating the next condition if the previous was met does not make sense from the business point of view.


edit: This question was identified as a possible duplicate of Elegant ways to handle if(if else) else.

I believe this is a different question (you can see that also by comparing answers of those questions).

Best Answer

Ideally I think you should extract your logic for getting the alert code/number into its own method. So your existing code is reduced all the way down to

{
    addAlert(GetConditionCode());
}

and you have GetConditionCode() encapsulate the logic for checking conditions. Maybe also better to use an Enum than a magic number.

private AlertCode GetConditionCode() {
    if (CheckCondition1()) return AlertCode.OnFire;
    if (CheckCondition2()) return AlertCode.PlagueOfBees;
    if (CheckCondition3()) return AlertCode.Godzilla;
    if (CheckCondition4()) return AlertCode.ZombieSharkNado;
    return AlertCode.None;
}
Related Topic