Wednesday, January 26, 2011

Erlang Guards for Happy Pandas

As a longtime C-like language developer (mostly Java lately) I find guard clauses (see here) tremendously useful. I vastly prefer a few simple checks at the top with either return or throw as appropriate to a code arrow (see here).

In the odd free minute I have been playing with Erlang and one of the features I am quite taken with is guards (ref manual, 7.24). For example, suppose you want to do something only if an argument is an int within a specific range. In Java one might do something like this:
private doStuff(int arg) {
  if (arg < 1 || arg > 65536) {
   throw new IllegalArgumentException("port must be between 1 and 65536; " + arg + " is invalid.");
  }
  //do stuff
 }
That looks kind of normal but what if there was a way to better split out the error handling from the happy path? Erlang guards offer exactly this functionality:
server(Port) when is_integer(Port), Port > 0, Port < 65536 + 1 ->
  io:format("Initializing echo on port ~w~n", [Port]);
%%look at me; I'm a completely different overload-esque function for the 'error' case
server(Port) -> 
  io:format("Invalid port specification; must be int, 1<=port<=65536. '~p' is invalid~n", [Port]).
The 'when ...' bit specifies under what conditions our function should run so in many cases we can trivially split the happy path from the sad panda branches.

I want this in Java damnit!

No comments:

Post a Comment