Why using fancy logic in a return statement is the wrong way to program

Yes, it looks impressive to write a function like

Return some_string.split(“”).map((val)=>(val+”-“).join()

This code takes a string, splits it into individual characters and adds “-“ to each one. Then the join() combines the chars back into a string.

It works just fine and looks impressive. However, this code can be difficult to read. It’s easy for us as developers to think that less lines of code is better, but overall it can make debugging much more complicated. Odds are, other devs will need to look back at your code in a few months. Even you may need to look back. This is where problems arise in terms of readability.

Readability

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

Martin Fowler

Now let’s try and make the above code a little more readable.

Let char_array = some_string.split(“”)

Let updated_arr = char_array.map((val)=> val + “-“)

Let updated_string = updated_arr.join()

Return updated_string

This code does the same thing as the code above, but it offers more readability to the humans reading it. Now if we needed to go back and look at the code, we can easily see how the logic works.

So if you have ever felt guilty for not writing code like the top leetcode answers, rest easy. It may look fancy. It my seem sleek. But for a programmer to not be frustrated while viewing your code. That’s the real win.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s