Friday, July 17, 2020

The Importance of Whitespace to Readability

Code is hard. One way to make it easier is to make it pretty. Even simple, short code can become difficult to reason about if it's all scrunched together:

That code is pretty simple, but difficult to reason about. The interspersed debug logging adds a lot of noise and detracts from overall legibility. Just spacing it out helps a lot:

What else can we do? The first declaration of ret is kind of pointless: let's move that closer to where it actually matters, and just return an empty object from the first guard clause. To make sure we print what's actually in the parameter we'll also JSONize it so we don't miss strings that look empty, but aren't. We'll also throw in a quick log wrapper.

The string pre-processing is fine as it is. We can ease our loop readability fairly easily:

Will we increase comprehension by switching to more-modern JS practices?

Kind of a toss-up, but I think so.

Ultimately, however, this is a function that would be better tested either via an actual test, or in the debugger. Logging is fine for long-running testing, but this function is short enough, and clean enough, that we might as well just set some breakpoints within the method, or at the call point.