My first rant…

A friend sent me a page about elm. It bemoans the idea of “Callback Hell” and purports to resolve the situation with a completely new language for web scripting… It didn’t take me long to feel the urge to violently disagree with the premise of the page. The author compares callbacks to “goto” statements.

A callback is simply a function, anonymous or named, that is passed into another method to be called later. jQuery loves callbacks, but my first exposure to them was in c++.

Here’s an example:

function Method1(callback){
    ...
    callback(someValue);
}

function Method2(myValue){
    ...
}

Method1(Method2);

The thing to keep in mind is that modern languages have “anonymous” methods, so you wouldn’t need to declare Method2…

function Method1(callback){
    ...
    callback(someValue);
}

Method1(function(myValue){...});

So, what’s wrong with the stance that callbacks are unreadable?

I don’t know… just the fact that they aren’t. Especially the example that he gives:

function getPhoto(tag, handlerCallback) {
    asyncGet(requestTag(tag), function(photoList) {
        asyncGet(requestOneFrom(photoList), function(photoSizes) {
            handlerCallback(sizesToPhoto(photoSizes));
        });
    });
}

getPhoto('tokyo', drawOnScreen);

I personally find that much more readable than his alternative:

getPhotos = lift sizesToPhoto . send . lift requestOneFrom . send . lift requestTag

(tagInput, tags) = Input.textField "Flickr Instant Search"

scene (w,h) img = flow down [ container w 60 middle tagInput, container w (h - 100) middle img ]

main = lift2 scene Window.dimensions(images (getPhotos (dropRepeats tags)))

especially given all the helper methods that he includes…

I certainly don’t think that callbacks should be singled out and compared to “goto”. Really, any function call is a glorified “goto”; they just have pretty curly braces to set them apart.

I can’t help but wonder if “goto” would have gotten such a bad wrap if the old text editors would have had shift-F12 support. I, for one, always regret never having the chance to use “comefrom”.

As anyone who works on enterprise level applications knows, code is messy. Especially when the bosses don’t care what it looks like, just how quickly you can write it. That’s why modern IDEs arose, because it’s easier to build a program to navigate your code for you, than to write code that’s easier to navigate.

So, you can go to great lengths, even writing new languages, to avoid using callbacks, or you could use them in a way that makes them easy to understand.

In then end, what really matters to me is that I get to keep my curly braces.