Site icon Being Software Craftsman (DFTBA)

Fail as early as possible

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.

RegisterUser(User user) routine and User has Name, Email and Password fields.

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:

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

Thus, the fail-fast/fail early would make the code simpler.

Guard clause in such scenarios helps us to improve understandability.

The end result:

Exit mobile version