DEV Community

Cover image for When you are writing code, do you "align the happy path to the left"?
Damien Sedgwick
Damien Sedgwick

Posted on

When you are writing code, do you "align the happy path to the left"?

The two code snippets in this post (which are images to help highlight the indent columns) are identical in terms of desired outcome, but they could not be any more different in terms of readability, cognitive load and maintainability.

Unnecessarily nested code is not something new to myself, but this idea of aligning the happy path to the left, is a new way of thinking about it for me.

Let's first look at some deeply nested code where the happy path is not aligned to the left. You will see there are 4 columns to reason about when trying to understand the potential outcomes.

Deeply nested code example

But why is it important?

The amount of time we spending reading code is far greater than the amount of time we spending writing code. So we should be doing all we can to enable ourselves to be able to quickly scan down one column to be able to see the expected execution flow.

So let's look at the same code, but with the happy path aligned to the left.

Happy path left aligned code example

Try aligning your happy path to the left in your next project and see how much easier it is to read your code.

Finally, the code snippets were taken from the book: 100 Go Mistakes and How to Avoid Them by Teiva Harsanyi - I recommend checking it out.

Top comments (2)

davesmith profile image
Dave Smith

Yep. I’m surprised how often I see the first example. I think some people were taught that your function should only have one return. I remember one professor teaching that style, but it was C code and some 20 years ago. It’s good to keep readability as a top priority and this style helps so much

damiensedgwick profile image
Damien Sedgwick

I could not agree more on making readability a top priority! Thanks for commenting.