LexCredo.Check.Warning.StructMatchInFunctionHead (LexCredo v0.2.1)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of normal and works with any version of Elixir.

Explanation

Match struct parameters in the function head, not in the body.

Destructuring a parameter as a struct at the top of a function body hides the expected type from both the reader and Elixir's type system. Declaring the struct in the function head makes the contract visible at a glance, enables multi-clause specialisation, and allows the type checker to infer the parameter type directly from the signature.

# BAD — struct type is hidden inside the body; type checker cannot
#        infer that `data` must be a %User{}
def process(data) do
  %User{name: name, email: email} = data
  send_welcome(name, email)
end

# GOOD — type is visible in the signature
def process(%User{name: name, email: email}) do
  send_welcome(name, email)
end

# GOOD — keep the original binding when you need the whole struct
def process(%User{name: name, email: email} = data) do
  send_welcome(name, email)
  audit_log(data)
end

Only top-level statements in the function body are checked. Struct matches that appear inside case, cond, if, with, or anonymous functions are left alone because they often serve a different purpose.

Check-Specific Parameters

Use the following parameters to configure this check:

:exclude_test_files

When true, skips test files. Default: false.

This parameter defaults to false.

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.