CodeVault - Invert your if statements
Logo picture

Code Cleanup - Invert your if statements

from Code Cleanup #5

You've all seen the literal side mountain of code, here's a refresh: if (candies.length > 0) { if (store.isOpen()) { if (store.allCandyIsLow()) { for (let candy of candies) { store.refill(candy); } notification('Store ' + store.Name + ' had its candies refilled.'); } else { console.error('There is still candy in the store'); } } else { console.error('No stores to put the candy into'); } } else { console.error('No candies'); }

This becomes really difficult to manage because

This hurts the code's readability, flexibility and maintainability (adding or changing the condition's order becomes tough).

Here's a practical solution that can be applied at any moment in development you want with doing these simple steps until there are no longer any exception cases nesting the main code:

The code from above should now look something like this: if (candies.length <= 0) { // or === 0 in this case console.error('No candies'); return; } if (!store.isOpen()) { console.error('No stores to put the candy into'); return; } if (!store.allCandyIsLow()) { console.error('There is still candy in the store'); return; } for (let candy of candies) { store.refill(candy); } notification('Store ' + store.Name + ' had its candies refilled.');

Albeit, the code block itself became larger but

What do you think? Are there any better solutions? Does this one have some critical flaws we missed? Ask away!

Get notified when a blog post is released

+ Free Clean Coding Guide