Comments

I’m an Open Source guy; I like using other people’s code, and from time to time reading through it to understand how it was built. Whenever code is commented I feel more relaxed reading through it; I get free insight into what the author was thinking while writing it.

JavaScript is a dynamically typed language, that means that there are no easy constructs in the language to specify which types and properties we’re accepting. To partially address this, docBlock comments were invented. They provide a structured way of showing all sorts of meta data about your function. Here’s an example:

/**
* Creates a function that sums two numbers.
* @param {Number} arg1
* @return {Function}
*/
function foobar (arg1) {
/**
* The inner function of foobar.
* @param {Number} arg2
* @return {Number}
*/
return function bin (arg2) {
return arg1 + arg2
}
}

That’s 10 lines of comments for 4 lines of code, a ratio of 2.5:1. That’s quite a few lines for something that’s a brief description + documentation of the types.

I was slightly annoyed by this, and figured it could be improved:

// Creates a function that sums two numbers.
// foobar(Number:arg1) -> bin(Number:arg2) -> Number
function foobar (arg1) {
return function bin (arg2) {
return arg1 + arg2
}
}

That’s 2 lines of comments for 4 lines of code, which to me feels much better. By adopting a haskellish notation we’re able to write things down more concisely and keep the code as focused as possible.

This is not the answer to JS’s lack of a proper type system, but I feel it does a better job than docBlock and will help my future self a great deal in making sense of my old code.


Originally published at github.com on March 18, 2015.