Horology and Programming

Do you know what a leap year is? You know, the extra day you get roughly every four years? It has its origin from the calendar system the majority of the world is currently using: the Gregorian Calendar, also standardised as ISO 8601.

In plain terms, the rule to determine whether a given year is a leap year or not is as follows:

  • If the year is divisible by 4, then it is a leap year; except
  • If the year is divisible by 100, then it is not a leap year; unless
  • If the year is divisible by 400, then it is a leap year

Confusing right?

Let’s try using a flow chart to visualize this:

See those nested ‘yes’ checks? They add complexity to understanding the algorithm. This also directly correlates to the code written in this style. Here is an example written in Haskell:

The nasty arrowhead pattern is difficult to read and comprehend. Your brain basically has to jump through hoops and maintain context to trace through the algorithm.

Can we do better?

Well yes, if we slightly rearrange the conditional checks:

The code suddenly becomes more declarative and easy to understand:

It even reads like plain English!

In conclusion, sometimes giving the problem statement a bit more thought and organisation can lead to better code.

Programmer | Watch enthusiast