The inspiration behind this blog post is, of course, the Clean code book.
Sometimes, people choose to use unnecessary deep conditionals.
They choose to return error/exception from else part of the deeply nested conditionals. It hampers the readability.
We will consider the use case of register user which requires three mandatory fields: Name, Email, and Password. (Let’s keep it simple.)
Let me walk you through a code that was created to showcase the problem of deep nesting. This was a part of the method “RegisterUser” that accept user object.
This code snippet creates a little-complicated decision matrix in your head, especially for the Else part.
When User’s Name is NOT empty && User’s email is NOT empty && User’s password is NOT empty then store user and also send a notification for that user.
Whereas Else part was more complicated and may read like:
- When User’s name is empty then throw an exception for the name is required.
- When User’s name is NOT empty but user’s email is empty then throw an exception for the email is required.
- When User’s name is NOT empty and the user’s email is NOT empty but the user’s password is empty then throw an exception for the password is required.
To make it simple, use guard clause to fail early or fail fast. All if clause in below snippet is guard clause.
Now, this one reads like
- Throw exception for the name as soon as the user’s name is empty.
- Throw exception for the email as soon as the user’s email is empty.
- Throw exception for the password as soon as the user’s password is empty.
- Otherwise, store user and send a notification to the user.
Thus, the fail-fast/fail early would make the code simpler.
Guard clause in such scenarios helps us to improve understandability.