Do you get confused when it's been a week since you last checked code you wrote and now you can't understand the conditions in it? Do you have 2+ nested conditionals? Are If Else conditions your favourite ones? In this article we'll go through a short example on why you should invert your conditionals when doing checks on functions, remove else statements and how they make reading code easier.
Use conditionals at the beginning of your functions and return early
When writting a function, execution should stop as early as possible when a condition is not meet:
// β Don't do this!
// Execution does not stop until the end, we have to go
// through all the code to understand why
// it does not work as expected
function execute() {
if (isAllowed) {
doSuccess();
} else {
doError();
}
}
// β
Do this instead. If condition is not meet, return early
// Otherwise, continue with execution
function execute() {
if (!isAllowed) {
doError();
return;
}
doSuccess();
}
With this example, we have removed an else statement and made the code easier to read. If condition is not meet, return error. Otherwise, keep going.
Help the author
As this is my first post on the platform, I'd like to know your opinion on which language should I use for the example (maybe multiple ones?), and also if you would like more in-depth examples instead of a short one.
Thanks a lot for reading, read you in the comments!
Top comments (0)