15 January 2015

Protecting Sensitive Data in Erlang with Function Callbacks

Function callbacks are one of those programming tricks that, once discovered, seem difficult for one to live without.

The concept of a callback is simple: you create a function, "package" it in some way, and pass it as an argument to another function, to be executed wholesale at a later time.  Here's what the process looks like in Erlang:

Why would one do this?  The main reason in most languages is to be able to build a function's logic in stages, particularly when such stages cross different compilation units, with the final stage being the callback.  There are other reasons, though.  Erlang, in particular, has one added benefit: when callback functions are implemented as anonymous functions, then assigned to a variable, it becomes much more difficult for the callback function to be executed unintentionally.  An Erlang module can't export variables, only regular functions, so putting an anonymous function in a variable means that only other functions launched with the callback as an argument will ever know that it exists.

My personal favorite usage of callbacks in Erlang is to protect functions which should only be available to authenticated users.  It's also handy for building GUIs with e.g. wxWidgets (and Erlang's wx module).  I'd be interested to hear what other uses people have found for function callbacks; suffice it to say, though, that I'm hooked on them.

No comments:

Post a Comment

Your comments are welcome. Please keep them professional, courteous, and respectful of the blog author and of other commentors.