Return as early as possible

Do you know how to check if the given year is a leap year or not?

Let us go through a simple leap year code snippet.

 

Tells you whether the given year is a leap year or not.

The above code snippets read like:

If a given year is divisible by 4, 100, and 400 then given number is a leap year.

If a given year is divisible by 4 and 100 but it is not divisible by 400 then it is NOT a leap year.

If a given year is divisible by 4, but it is NOT divisible by 100 then it is a leap year.

Otherwise given number is NOT a leap year.

Did you realize that readability is poor when you use deeply nested conditionals?

Even a simple program becomes difficult to understand.

This is called Arrow anti-pattern because too many nested if represent an arrow-like shape.)

Readability could be achieved by returning as early as possible.

Let’s see via example.

Returning as early as possible

Don’t you think the second one is easier to understand?

It reads like

If a given year is divisible by 400 then it’s a leap year.

Otherwise if divisible by 100 then it’s NOT a leap year.

Otherwise if divisible by 4 then it’s a leap year.

Oherwise it’s NOT a leap year.

Dattatray Kale | Being software craftsman
I am an application developer based in Pune, India. I am willing to wait for the right opportunity – Datta CV PRACTICES…blog.beingcraftsman.com

Dattatraya Kale

Aspiring agile software craftsman, clean code, polyglot, in love with different programming paradigm. I am on a never-ending journey towards mastery of software.

Leave a Reply