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