I often see Erlang functions return ok, or {ok, <some value>}, or {error, <some problem>}.
Suppose my function returns an integer N. Should my function return just N, or {ok, N}?
Or suppose my function includes the call io:function("Yada yada"). Should it return ok or nothing at all?
Or suppose I'm making a record or fun. Should I return {ok, R} or (ok, F}?
Thanks,
LRP
It's a matter of style, but making reasonable choices goes a long way toward making your code more readable and maintainable. Here are some thoughts based on my own preferences and what I see in the standard library:
{ok, _} or ok. Good examples are: orddict:find/2 and application:start/1. We do this so both cases can be easily pattern matched when making the call.foo(bar(N)) may not work if bar/1 returns {ok, _}. Good examples are: lists:nth/2 and math:cos/1.ok or true as opposed to whatever the last returned value in the function happened to be. Good examples are: ets:delete/1 and io:format/1.Suppose my function returns an integer N. Should my function return just N, or {ok, N}?
If there is no possibility of error at all, or any error indicates a programming error, N. If there may be a good reason to fail, return {ok, N} (and {error, Reason} in case of failure).
Should it return ok or nothing at all?
In Erlang, you can't return nothing at all. If you don't have a meaningful return value, ok will do fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With