What is preferred code style for long guard clauses?
def verify(d1, d2) when is_integer(d1) and d1 > 0 and d1 < 101
and is_integer(d2) and d2 > 0 and d2 < 101 do
...
end
What is preferred code style for long guard clauses?
def verify(d1, d2) when is_integer(d1) and d1 > 0 and d1 < 101
and is_integer(d2) and d2 > 0 and d2 < 101 do
...
end
If I can name that condition or I do use it in multiple def
s, I try to make a macro from it.
If not, I do insert a linebreak before every and
/or
and also I do indent according to surrounding parenthesises.
I think it’s the following, as per this style guide:
def verify(d1, d2)
when is_integer(d1) and d1 > 0 and d1 < 101
and is_integer(d2) and d2 > 0 and d2 < 101 do
...
end
I usually split the part after the where on multiple lines, each starting with the next and
. If that too is unreadable, it might make sense to put the guard in a macro, so you can just say e. g. where is_small_num(d1) and is_small_num(d2)
which is easier to understand in the context of the function, and also easier to manage if multiple functions need the same (/similar) kind of clauses.
Also an option is to place the and
s at the end of each line instead of the beginning and align the predicates.
def verify(d1, d2)
when is_integer(d1) and d1 > 0 and d1 < 101 and
is_integer(d2) and d2 > 0 and d2 < 101 do
...
end
The same styleguide doesn’t state this explicitly, but it does have a very similar rule for binary operators.
This does look cleaner