Skip to content
Sarj Code Standards

prefer-optional-composite

Review related optional fields as one optional composite value.

Why

Several nullable fields with a common record prefix can scatter one optional value across a larger model, requiring repeated presence checks and obscuring which partial states are intentional. A nested value can give that concept one boundary while retaining independently nullable children.

Fix

Review whether the fields represent one value and, if so, introduce a typed composite with one optional outer field. Preserve valid partial states, omitted-key behavior, defaults, aliases, validation and wire/storage compatibility. Keep independent optional children nullable. A shared prefix does not prove that all fields must be present together.

Examples

Before — flagged Review a usage value split across nullable fields
app/models.py
from pydantic import BaseModel
class State(BaseModel):
in_use_by: str | None
in_use_by_name: str | None
in_use_since: str | None
After — preferred A present usage value can still have an unavailable actor name
app/models.py
from pydantic import BaseModel
class Usage(BaseModel):
actor_id: str
actor_name: str | None
since: str
class State(BaseModel):
in_use: Usage | None