ForgeCredoChecks.LargeStruct (forge_credo_checks v0.7.0)

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 high and works with any version of Elixir.

Explanation

A struct with 32 or more fields loses the BEAM's flat-map optimization.

Why

The runtime stores a map with at most 32 keys as a "flat map": a shared sorted key tuple plus a compact value array, with cheap lookups and updates. At 32 keys and above the map becomes a hashmap (a HAMT), which uses more memory per instance and turns those cheap operations into tree traversals. A struct is a map, so a struct this wide pays the cost on every instance, often across many in flight at once.

A struct that has grown past this point is usually carrying several unrelated concerns that want to be separate, nested structs.

Bad

# 33 fields, all on one struct
defstruct [:f1, :f2, :f3, :f4, :f5, :f6, :f7, :f8, :f9, :f10, :f11]

Good

# grouped into focused sub-structs
defstruct [:identity, :config, :working_state]

Configuration

max_fields (default 32) is the field count at which the check fires.

Check-Specific Parameters

There are no specific parameters for this check.

General Parameters

Like with all checks, general params can be applied.

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