Return as early as possible

Dattatray Kale
Technogise
Published in
2 min readAug 14, 2019

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.

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.

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.

Otherwise it’s NOT a leap year.

Originally published at https://beingcraftsman.com on January 11, 2019.

--

--

Dattatray Kale
Technogise

Software Craftsman & Cloud Engineer with 13+ years' expertise. Proficient in React, Angular, .NET, Node.js, Java, AWS, Azure. Proven leader in team building.