Saturday, June 11, 2016

guard vs. if-let (Or: The Cost of Pyramids of Doom)

Recently read a post by Natasha The Robot after Apple introduced the 'guard' keyword in Swift 2.0. The article itself has good examples of code implemented with if-let vs guard, but the more compelling part of the post were in the comments themselves.

The majority of the commenters were focused on the example code that performed error checking within a constructor. Some thought it violated the single responsibility principle whereas others focused more on the benefits of the keyword itself. While I did enjoy the single responsibility discussions, the stuff that really made me sit back in my chair and think was the idea of code readability. 

The concept of the pyramid of doom was something I recently read while learning Swift. In my day we termed it nested ifs. I always ascribed to the theory that a function should have a single point of return. That being the case I would use nested ifs in order to perform error checking, for example, before actually executing the function and assigning a return value. Then at the end of a few levels of closing braces I would return the result. 

My contemporaries at work prefer the immediate returns or immediate exception throws once a problem was discovered. In my mind this was a perversion. Multiple paths of return for a function? How messy. Of course their functions didn't really suffer from nested if syndrome. 

Now I understand their perspective from the readability point of view. A new dev stepping foot in the code will likely find it easier to understand the function. But my perspective had always been, why are curly braces so scary? Why is a developer's attention span so short that they forget what we are doing halfway into a function? And shouldn't a function be written short to begin with in order to aid in readability? 

Nowadays I feel that holding on so tightly to those philosophies makes me a cranky old developer, yearning for the days where we'd walk barefoot to school, in the snow, uphill both ways. The reality of software development is that speed of development is a valuable commodity. In the commercial world time to beta, time to market, they're all critical. 

I used to smirk with derision at developers who used Visual Studio and their Intellisense while I coded C in vim and hand-wrote my makefiles. What I didn't understand is that Intellisense isn't a crutch. Readability of code isn't a crutch. They are two methods by which developers can understand and write code faster and with less errors. The cost of pyramids of doom is time. There is never enough time in software development; why make it harder on ourselves? Consider me converted.

No comments:

Post a Comment