In defence of literate programming


We tend to write code differently when we know that someone will be reading it, don’t we … [Josh Johnston, X-Team]

The thing is, you should always try to write (and rewrite) your code so that it is as clear as possible. Not only because of your possible code-reviewer, but also because of yoour future self. What may seem obvious to you at the time when you are writing code, might be quite unclear at the time when you read it half a year later. You will spent long time just trying to understand your old code. So, next time you are programming something, do your future self a favour: Write lots of explanatory comments.

Write comments about why something is implemented the way it is, what the context was at the time of developement, perhaps why customer wants it etc. It will not only help you in the future, but by forcing you to slow down and think, you will end up writting better code.

comments

 

As for example you can look at source code of AngularJs. It is very well written and very well commented. It is a pleasure to read such a code.

/**
 * @private
 * @param {*} obj
 * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
 *                   String ...)
 */
function isArrayLike(obj) {

  // `null`, `undefined` and `window` are not array-like
  if (obj == null || isWindow(obj)) return false;

  // arrays, strings and jQuery/jqLite objects are array like
  // * jqLite is either the jQuery or jqLite constructor function
  // * we have to check the existance of jqLite first as this method is called
  //   via the forEach method when constructing the jqLite object in the first place
  if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;

  // Support: iOS 8.2 (not reproducible in simulator)
  // "length" in obj used to prevent JIT error (gh-11508)
  var length = "length" in Object(obj) && obj.length;

  // NodeList objects (with `item` method) and
  // other objects with suitable length characteristics are array-like
  return isNumber(length) &&
    (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
}

Now the same code without all those comments. It works the same, that’s for sure, but which one would you to work with?

// same code as above but without comments
function isArrayLike(obj) {
  if (obj == null || isWindow(obj)) return false;
  if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  var length = "length" in Object(obj) && obj.length;
  return isNumber(length) &&
    (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
}