Should functions that return tuples, always return tuples?
For example, I have a function is_user_name_allowed
that returns a tuple in this he form if the username is not allowed:
{false, ["Reason 1","Reason 2"]}
If the I want to return true, is there any convention/benefit to returning a tuple as opposed to simply returning true
? ({true}
vs true
)
The convention is to just use true
in this case. The same style is used in many OTP libraries, e.g. lists:keyfind/3
.
1
You may save some time and memory by not having to construct and evaluate a tuple if you just return a bare-naked atom. Write a benchmark, run several million of each way through it and you’ll know for sure.
That aside, it doesn’t really matter:
handle_result(true) -> do_true_things();
handle_result({false, Reasons}) -> do_false_things(Reasons).
some_function() -> handle_result(is_user_name_allowed("bob")).
The first version of the function would work just the same if it was specified as handle_result({true})
and is_user_name_allowed()
returned a tuple.
More important is the safety aspect. Make sure you use the matcher to handle the result, which will give you an implicit check that it was valid without having to do it after each call. If something goes wrong, a function_clause
error will bring it to your attention.
What I would not do is return a tuple that’s always structured the same way:
{true, []}
{false, ["Ugly", "Mother dresses him funny"]}
While you could match them, it leaves open the possibility that a caller will do…
{Result, Reasons} = is_user_name_allowed("bob")
…and not validate the result.
2