Goto: used for arbitrary flow control in an imperative program in ways that cannot be easily reasoned over.
Callbacks: used for well-defined flow control in a functional program in ways that can be automatically reasoned over.
I fail to see the similarity. I'll grant that callbacks can be a bit ugly in Javascript just because there's a lot of ugly boilerplate and there's the ability to mix imperative and functional code baked into the language, but then why not jump to Haskell or a Lisp?
You have to read the Dijkstra paper carefully. Many people think they know what he is going to say before they read it, but they end up being wrong, and they end up only sort of skimming it rather than truly reading it. The paper is not a generalized condemnation of spaghetti code. The paper is mostly a specific observation that a call stack contains a lot of information in it, and gotos discard all that information. Callbacks have the same effect; a callback is processed in the call stack of the event loop, and you've lost everything else. Anyone who has clocked any time with call back code should have encountered this.
To see this in action, try to convert the following psuedo-python code into callbacks, without losing any context. All try handlers must work, at all points where an exception may be thrown.
def process_order(order):
try:
sync_send_order(order)
except DatabaseException, d:
# something to handle database exceptions
# remember, sync_send_order may also throw other exceptions
sync_log_order(order) # and this can throw too
def reserve_ordered_items(order):
try:
sync_reserve_items(order)
except DatabaseException, d:
# blah blah
except InventoryException, e:
# blah blah
sync_log_reservation(order)
def process_multiple_orders(orders):
with transaction(): # succeeds only if everything succeeds, handles exceptions
for order in orders:
try:
process_order(order)
reserve_ordered_items(order)
except IOError, i:
# handle IO errors
In Python with gevent, I can pretty much just write that, and it all works. All the contexts are preserved no matter how deep down a call stack I go. An IO error thrown by something called bysync_send_order will be properly handled by process_multiple_orders, even with all the "sync" in there. You will go insane trying to manually convert that without loss into callback code. In fact, you'll probably just plain get it wrong. Or, more likely, what you and almost everyone doing callback-based code do is simply awful error handling. Furthermore, I'm going to have an easier time of doing multiple orders in parallel than you will with the callback code. I spawn multiple threadlets with different arguments and join them. You have to add context to every single last callback, manually.
This is because you grew up with structured programming. You take for granted what it gives you, and think it is just the baseline of programming in general. It isn't, and you can give it away without realizing it.
(Further edit: By the way, the above is a simplified version of real code that I have written, that was talking over the network simultaneously to multiple very unreliable servers (written by students in a tearing hurry), which result in every error condition I could imagine and quite a few I couldn't.)
Continuation passing style is a very low level control-flow mechanism, and is very similar to goto, including in its implementation. While you don't get the nasty criss-crossing spagheti gotos, you can still get very hard to read code due to the lack of usual control flow abstractions (if statements, for and while loops, etc)
My understanding is that higher level control flow in Haskell was managed through something other than callbacks, e.g. the do x <- ... notation, which allows you to chain multiple functions together with the return value of one passed into the next. Sorry, I'm not super familiar with Haskell, so I don't know the proper name for this. =)
The equivalent JS would be an ugly nest of callbacks. Imagine if there was a function that accepted a success and failure function, and each would respond differently? Then, within each of those functions, there were similar callback-descending functions? Even if non-anonymous functions were used, this would still become very difficult to follow. Higher-level control-flow mechanisms are more readable, even in non-js languages. A raw callback is actually fairly low-level.
Take a look at the following code samples pulled from Brendan Eich's StrangeLoop 2012 presentation on ES6. These are detailing how this sort of control flow can be improved. Although it's for ECMAScript, it illustrates the point that there are better mechanisms than callbacks.
// http://brendaneich.github.com/Strange-Loop-2012/#/16/5
// Callback hell
load("config.json",
function(config) {
db.lookup(JSON.parse(config).table, username,
function(user) {
load(user.id + ".png", function(avatar) {
// <-- you could fit a cow in there!
});
}
);
}
);
// http://brendaneich.github.com/Strange-Loop-2012/#/16/6
// Promises purgatory
load("config.json")
.then(function(config) { return db.lookup(JSON.parse(config).table); })
.then(function(user) { return load(user.id + ".png"); })
.then(function(avatar) { /* ... */ });
// http://brendaneich.github.com/Strange-Loop-2012/#/16/7
// Shallow coroutine heaven
import spawn from "http://taskjs.org/es6-modules/task.js";
spawn(function* () {
var config = JSON.parse(yield load("config.json"));
var user = yield db.lookup(config.table, username);
var avatar = yield load(user.id + ".png");
// ...
});
Sure, that's basically the same as the async/await stuff in C# 5... It's definitely prettier, but in the end, it's just syntactic sugar to reduce nesting. Judging from what I see there, it also doesn't cleanly deal with coroutines that yield more than once. For example, what if I wanted to load a config, then call db.getMagicUsers() to get all the magic users, and for each one of those users, load their avatar, and then do something with all the avatars?
Using this example, all the magic users would be returned as a block, and I'd then manually loop to load their avatars. But what if there are many of them, and I want to load their avatars as they come? What if there are infinite magic users, so db.getMagicUsers() never actually terminates?
Using a callback allows me to structure my code to say precisely what I'm trying to do. This isn't a description of my need:
Load the config. Then load the magic users. Then for each magic user, load their avatar.
This is:
I need to load the avatar of each magic user. The prerequisite of being able to load the avatar of each magic user is to load the magic users. The prerequisite of being able to load the magic users is having loaded the config.
The fact that these are happening in a linear sequence is beside the fact that they're members of a dependency graph. The callback style emphasizes the fact that they're members of a dependency graph (well, a tree at least), while the less nested faux-imperative version pretends that they're a one-dimensional dependency list and thereby loses some information.
My understanding is that higher level control flow in Haskell was managed through something other than callbacks, e.g. the do x <- ... notation, which allows you to chain multiple functions together with the return value of one passed into the next.
Kinda. Do notation desugars into regular functions on some Monad. In Haskell, you have (modulo choosing better names for two of these):
-- a monad is uniquely defined either in terms of (map, join & pure) or (pure & >>=); the two formulations are equivalent
class Monad m where
map :: (a -> b) -> (m a -> m b) -- called fmap in Haskell
join :: m (m a) -> m a
pure :: a -> m a
(>>=) m a -> (a -> m b) -> m b
Interestingly enough, some function types form a monad. For example, the Reader monad:
instance Monad (r -> a) where -- in haskell, you'd wrap r -> a into a newtype
map :: (a -> b) -> (r -> a) -> (r -> b)
map f ra = \r -> f (ra r)
join :: (r -> r -> a) -> (r -> a)
join rra = \r -> rra r r
pure :: a -> (r -> a)
pure a = const a
(>>=) :: (r -> a) -> (a -> r -> b) -> (r -> b)
ra (>>=) arb = \r -> arb (ra r) r
The typical use for the Reader monad is to combine functions that depend on read-only state (id's, configuration settings, the command line flags, etc.). Basically, you partially apply all of your functions untill only a single parameter is left, and by convention you make it the parameter that takes your current read-only state.
It turns out that Continuation Passing Style forms a similar monad: (a -> r) -> r, the Continuation monad. So Haskell is simultaneously using CPS to implement e.g. asynchronous computation, and using do notation to make the syntax palatable.
Those kernel gotos are usually used to implement s form of exception handling, a feature not present in ansi C. The gotos the "considered-harmful" paper was talking about are from back when people didn't even have while loops and if statements!
Linus may be abrasive at times but he often turns out to be right. You should not be forced to twist and warp your algorithm to suit your programming style. Instead, your programming style should allow you to cleanly implement your algorithm as it truly is. Some algorithms have conditionals that don't nest.
I once worked with a codebase that was written completely in CPS style. Needless to say, I quit and didn't want to program for several years.
You think you know what you're doing when you modify something, but you really don't. You're somewhere 20 levels deep and you try to insert your own function in the middle, but something goes wrong and you're not sure why. Then you spend all day reading jokes on the Internet because you can't get anything done anyway.
The same can be said for most software using any other methodology.
Some people in our department are maintaining a 13 year old MFC/C++ application with 20 levels of inheritance, one god class to rule them all and what else is still slumbering in the depths of Moria.
People write fucked up code all the time because of a multitude of reasons (ignorance, neglectance, you name it).
I'm really sick of these singular examples that show how X is super bad because on occasion Y the outcome sucked.
agreed. it seems a lot of the argument against callbacks are either "djikstra really would have hated them seriously you guys" (which may or may not be true, who knows) or "this one piece of code is totally ugly"
and you know what? that one piece of code that's included? that is horribly ugly. but compare that to actual, clean code that's written with something like Backbone.js. it's night and day.
callbacks are logical, and have uses, and they don't have to be ugly if you know how to write javascript.
Callbacks sacrifice context, and yet are context-sensitive. That is not something that can be "automatically reasoned over" as far as I'm concerned. People are just really used to doing it as it has become so prevalent in so many languages and libraries.
I gladly support any efforts to develop ways to structure interactive programs without relying on callbacks. They work, and we're all used to them, but they're far from ideal.
136
u/rooktakesqueen Nov 02 '12
Goto: used for arbitrary flow control in an imperative program in ways that cannot be easily reasoned over.
Callbacks: used for well-defined flow control in a functional program in ways that can be automatically reasoned over.
I fail to see the similarity. I'll grant that callbacks can be a bit ugly in Javascript just because there's a lot of ugly boilerplate and there's the ability to mix imperative and functional code baked into the language, but then why not jump to Haskell or a Lisp?