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

Damien Sedgwick - Mar 20 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player