Take the following code:
def drive(%User{name: name, age: age}) when age >= 18 do
"#{name} can drive"
end
def drive(%User{name: name, age: age}) when age < 18 do
"#{name} cannot drive"
end
In the code above, the pattern matching of the user is extracting fields for further usage (name) and for pattern/guard checking (age). While the example above is fine, once you have too many clauses or too many arguments, it becomes hard to know which parts are used for pattern/guards and what is used only inside the body. A suggestion is to extract only pattern/guard related variables in the signature once you have many arguments or multiple clauses:
def drive(%User{age: age} = user) when age >= 18 do
%User{name: name} = user
"#{name} can drive"
end
def drive(%User{age: age} = user) when age < 18 do
%User{name: name} = user
"#{name} cannot drive"
end
This is also related to "Complex multi-clause function".
Take the following code:
In the code above, the pattern matching of the user is extracting fields for further usage (
name) and for pattern/guard checking (age). While the example above is fine, once you have too many clauses or too many arguments, it becomes hard to know which parts are used for pattern/guards and what is used only inside the body. A suggestion is to extract only pattern/guard related variables in the signature once you have many arguments or multiple clauses:This is also related to "Complex multi-clause function".