select * from ideas

where topic='technical' and state='exploratory'

Revealing Intent in JavaScript

Uncle Bob’s book Clean Code has a chapter called Meaningfull Names. In this chapter Uncle Bob offers advice, tips, tricks and ideas how to reveal the intention of the code. There is web of pages on the content creation wiki C2 with a similiar focus. The page Intention Revealing Names is a good starting place.

The goal of intention revealing code is to aid in Hermeneutics, a fancy word for

the art and science of text interpretations.

The motivation behind intention revealing code is the insight that the amount of code-reading far outweighs the amount of code-writing. Jeff Atwood wrote a nice blog about the issue: When understanding means Rewriting.

I recently developed a style which communicates the intent of code very clearly. In this blog I would like to share my insights, hoping that others may benefit. Lets start with an example.

Example of intention revealing code
1
2
3
var an_array = ['a', 'b', 'c', 'd'];

swap('b').and('d').in(an_array);

I would wager that the intent of the above code is clear. In my opinion the code is very readable, focussing on the What instead of the How. It uses a fluent interface, as introduced by Martin Fowler. A possible implementation is given below.

Possible implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var swap = function(this_element) {
    return {
        and : function(that_element) {
            return {
                in : function(an_array) {
                    var index_of = function(element){ return an_array.indexOf(element); };
                    place(this_element).at(index_of(that_element)).in(an_array);
                    place(that_element).at(index_of(this_element)).in(an_array);
                }
            };
        }
    };
};

var place = function(element) {
    return {
        at : function(index) {
            return {
                in : function(an_array) {
                    an_array[index] = element;
                }
            };
        }
    };
};