Continuation-Passing Style: Don't Overdo it

Continuation-Passing Style(CPS) is a style of programming that's useful for a number of use-cases, but you shouldn't get carried away and start writing all your programs in this style. Here, I am going to list 3 disadvantages of programming in this style.

Code Size

Unless your language has specific language support for writing in Continuations(e.g. Haskell), your code will have more bloat.

Example, here's a sqrt function in direct style:

function sqrt(a, b){
    return a * 2 + b * 2;
}

Here it is in CPS:

function sqrt(a, b, callback){
    multiply(a, 2, function(a2){
        multiply(b, 2, function(b2){
            add(a2, b2, callback);
        });
    });
}

Readability

The direct style is generally easier to read/understand. Take the previous sqrt example, the CPS version introduces 2 extra variable names: a2 and b2, which increases the mental load of somebody trying to read the program.

Code is Coupled to Ordering of Operations

With CPS-Style code, the order of your operation affects the structure of your code. Again, taking the sqrt example. This time, let's rewrite the direct-style version to:

function sqrt(a, b){    var a2 = a * 2;    var b2 = b * 2;    return a2 * b2;}

Here, the statements var a2 = a * 2; and var b2 = b * 2; are completely separate and independent. I could swap their order without changing the code's behavior. In the CPS-Style, the whole thing is one big statement, and therefore, to reorder the sequence of operations, it is necessary to mentally unwrap the layers of closure functions and pull out just the right ones and then put them back together. In this simple example, it wasn't actually that hard, but imagine if the code was more like this:

function sqrt(a, b, callback){    multiply(a, 2, function(a2){        /* code */        multiply(b, 2, function(b2){            /* code */        });        /* more code here */    });}

Basically, code in this style is much harder to decouple into smaller independent parts. Libraries like Do and node-promise exist to compensate for this problem, but they IMO are still a far cry from the plain ol' direct style.

The point here is that there are definite disadvantages to writing code in the Continuation-Passing Style. I am not saying that you should not use CPS, but that you should have good reasons for using it - good enough to offset its disadvantages.

blog comments powered by Disqus