Untangling conditionals with IF-inversion
Untangling conditionals with IF-inversion

Untangling conditionals with IF-inversion

This is a very common trick, but there are still some developers around who struggle with applying it. The idea is to cut through the complexity of IF/ELSE structures and make the code more understandable, by treating the exceptional cases first.

Here are two variants of the same validation function, which should reject a user’s application if they are underage or if they have a previously approved application. They are written in PHP but the concepts can be applied to any programming language:

https://gist.github.com/calina-c/4e626d9e435094025f6e9bbba1e9df0ahttps://gist.github.com/calina-c/9535b937c459e2de3b45fb97869b6443

The result is the same, as you can see for yourself by running the full-length gist from here: https://gist.github.com/calina-c/96a1e945a55a41cada6db92531df1d92

The steps are as follows: identify the possible failure cases. Treat them using a simple IF structure and use “return” to stop execution of the validation function. Rinse and repeat. In the end you are left with a single case, which can be treated directly, without the need for “else” blocks.

The length of the functions is more or less equivalent, but the readability is highly improved and your fellow developers will thank you for your clarity.