The other day I came across a hilarious tweet
It’s funny indeed, but at the same time it’s the typical showcase of Cargo Cult Programming — ritual inclusion of code or program structures that serve no real purpose. It might seem to be an edge case, a funky thing that couldn’t be really met in the real-world, but let’s review a piece of code from the highly rated — more than 8000 Github stars — project called Calypso.
Calypso is the new WordPress.com front-end — a beautiful redesign of the WordPress dashboard using a single-page web application, powered by the WordPress.com REST API. Calypso is built for reading, writing, and managing all of your WordPress sites in one place.
It’s clearly on the cutting edge — react, redux, webpack, babel and other 150 npm packages it depends on should allow contributors to write a modern, clean, easily readable, highly maintainable code, right? Let’s take a look. But first things first, here is a crash course on redux for those who are not familiar with it — the reducer is a pure function that takes two objects, performs some calculation and returns the new object, that’s basically it. A primer on reducer is adding a new item in the TODO list :
Multiple reducers can be composed within the single object where the keys are reducers names and the values are reducers functions. Here is the slightly modified code for one of the many Calypso reducers, extracted from here.
- const declarations
- computed property names
- Pulling fields from objects passed as function parameter
- Arrow functions
- Spread Object properties — it’s not even in the specification yet, but we can use it today, how cool is that!
- Shorthand Property Declarations
But to me — and I guess that I’m not alone — this piece-of-art seems too fancy, too difficult to understand, and if I were to implement the same functionality, I would do it slightly differently. This reducer updates the state of a given post publication on a given web-site, here we go:
- Original — full : 2012 bytes, minified : 1524 bytes
- Modified — full: 1390 bytes, minified : 1019 bytes
The difference might look minor, but in a large project, like Calypso, hundreds if not thousands lines of code written in the name of Cargo Cult might add up to the significant increase in JS scripts size which is one of the key points to avoid in order to optimize the critical rendering path.
Moreover, the modified version of a reducers works FASTER. I put together JSPerf test to demonstrate that, here is the screenshot of test run in Chrome:
Note that modified version of the code also leverages ES6 features, but it does not try to use each and every buzz-thing in the name of fanciness. In the end the code is more readable, faster and smaller. And I can optimize it even further! Let me finish this post with one of my favorite quotes about programming.