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:

  • 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.

The end result:

4 responses to “Fail as early as possible”

  1. Kiran Tate Avatar
    Kiran Tate

    Usefull✌..

    1. Dattatray Kale Avatar

      Thanks, Kiran!

  2. ravi Avatar
    ravi

    Nice Datta!

  3. सागर Avatar
    सागर

    This is an brilliant idea

Leave a Reply

I’m Datta

Welcome to BeingCraftsman — where software architecture is treated as a long-term responsibility. I’m a Software Architect and Cloud Lead based in Pune, India, with over a decade of experience designing scalable systems, guiding teams, and making practical engineering decisions. This space is about clarity in architecture, reliability in systems, and leadership that helps teams build software that lasts.

Let’s connect

Linkedin

Discover more from Being Software Craftsman (DFTBA)

Subscribe now to keep reading and get access to the full archive.

Continue reading