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).
- My question is checking for the first accepting condition to end quickly.
- The linked question is trying to have all conditions to be accepting in order to do something. (better seen in this answer to that question: https://softwareengineering.stackexchange.com/a/122625/96955)
if OK1 then if OK2 then if OK3 then … do-happy-stuff … else handle3 end-if else handle2 end-if else handle1 end-if
– PJTraill Jan 12 '18 at 21:16To everyone else - Thank you for so many interesting answers and opinions - when I get back to work I'll check which answer works the best with my code.
– Ev0oD Jan 14 '18 at 15:54if (! checkCondition1()) { if (! checkCondition2()) { ... } else { addAlert(2); } } else { addAlert(1); }
. The answer to that question would be to invert the tests and rewrite the code as expressed in this question. But that's not what the supposed duplicate asks. This is a very different question. – David Hammen Jan 15 '18 at 09:10I cannot remove the elses
. You can. State Machine design pattern.evaluating those conditions is expensive
, and State Machine will help with that, too: you won't have to check even for the first expensive condition every time, you'll be in the state to do the thing, and will just do the thing. And then when conditions actually change, instead of changing the fields in the class(es), you tweak the state of your machine respectively, and so you only do the expensive part with conditions once, instead of doing it every time you call that outer function. – KulaGGin Feb 20 '23 at 12:36