ConFoo is a multi-tech conference hosted in Montreal, Canada, at the beginning of the (still very cold over there) month of March. So after a comfortable intercontinental flight and checking in at my Airbnb, I walked to downtown Montreal and immersed myself into my first tech conference ever. As a classicist recently turned developer, I really looked forward to getting a taste of as many new technologies as possible. But in the end, the stuff that really made an impression was all about code quality: how to write better code. That is to say: more testable, more readable and more maintainable.
Developing in Node.js, or in any other language for that matter, can lead to a lot of boilerplate code. I live by the adage that a good developer is a lazy developer. That’s why I would like to share some ways in which to write less and cleaner code in Node.js both in application code as in unit testing. This contribution is inspired by the awesome talks by Gleb Bahmutov and Christopher Neugebauer.
ES6 goodiesSeparate arguments
In ES5, we would write the following in order to access all arguments after y:
In ES6, we can use the rest operator:
Computed Keys
Every javascript developer has written the following code:
But in ES6, we can use computed keys:
Argument binding
Given this example of express code:
Wouldn’t it be awesome to be able to write just this?
authGet('/repos', ctrl.getRepos);
In Javascript, we can easily bind arguments to a function using the bind function:
But in our example, we want to bind the second and third argument. This is not possible using bind, but the npm module spots allows us to do just that:
And now it is possible to define an authenticated route in a more readable and concise way:
authGet('/repos', ctrl.getRepos);
Property based testing
Good unit testing requires a lot of test cases. Let’s take the add function we defined above. There are a few cases we need to check in our tests:
Using property testing and the excellent jsverify module (inspired by the quickcheck haskell library: https://hackage.haskell.org/package/QuickCheck), we can avoid a lot of boilerplate. And as a bonus, the module will by itself check a lot of edge cases:
This is just the tip of the iceberg for property based testing. By writing general properties for our scenario, jsverify generates by default 100 test cases, checking most – if not all – edge cases. This makes the hard job of thinking of all the edge cases when testing algorithms, a breeze. And as a consequence, this lazy developer can become even more lazy and concentrate on the fun parts of coding.