Human Readable Code or Why I Don’t Like if Statements

Written by visikov | Published 2017/03/21
Tech Story Tags: javascript | programming

TLDRvia the TL;DR App

In this post I’m going to go over why if statements should be removed from your code. I’m not saying that you should go back and remove all if statements from all the code that you’ve written or start some major refactor. I’m just proposing a more human readable style of writing code.

It’s easy to write code that works and executes. The machine doesn’t care how you structure your code or what you name your variables. The difficult part is writing code that other people can look at and quickly understand.

This is better demonstrated with examples. Let’s take this piece of arbitrary code:

This is a fairly simple example and shouldn’t take you very long to parse through. However, this simple little method can very quickly evolve into something that’s unmaintainable, infuriatingly hard to read and a nightmare to test.

Not only can we make this more human readable but we can reduce the cyclomatic complexity of this method if we remove the if statements and abstract away some of the business logic into simpler more terse/descriptive methods.

Image borrowed from Yeray Darias

It’s relatively simple to get rid of these if statements and turn our simple example into a more declarative style. First, we can turn every expression inside our if’s into it’s own function.

Our simple example is starting to shape up. Now, we can tell what those conditionals are checking for. Unit-testing just those conditionals is possible, too, since they’re encapsulated within their own methods.

However, we can take this a step further…

There’s that nasty forEach loop in there. It sticks out like a sore thumb. We can get rid of it with a .map() and abstract that logic away into it’s own method.

While we’re at it, let’s get rid of both of those if statement. We can replace them with ternary operators. Again, simpler to just demonstrate:

Conclusion

Anyone who has to maintain this code is going to have a much easier time understanding what the getRelatedArticles method is doing. It’s also a lot easier to add on more methods into the article parse method, parseRelatedArticle, in comparison to how this file used to look like.

Each of these methods performs a highly specific function which makes unit-testing this file much better.

If an error occurs at run time the stack trace will tell you exactly which method failed, so this makes debugging much simpler than having to check what line failed and trace what exactly is happening through the original getRelatedArticles method.

This, of course, is a completely arbitrary example. I trust that you’ll be able to extrapolate from this.


Published by HackerNoon on 2017/03/21