Code style for long guard clauses?

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
1 Like

If I can name that condition or I do use it in multiple defs, 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.

2 Likes

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

4 Likes

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.

2 Likes

Also an option is to place the ands 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.

2 Likes

This does look cleaner

2 Likes