Skip to content
Sarj Code Standards

prefer-explicit-value-model-construction

Prefer declared validation and explicit factories over value-model initialization hooks.

Why

Handwritten post-initialization hooks hide validation and normalization in a separate construction phase. Repeated scalar checks can diverge from field contracts, while implicit mutation and effects make a value model harder to construct and reason about.

Fix

Express scalar constraints in Pydantic fields and keep cross-field validation in an explicit native validator. Use a named typed factory for deliberate construction work or side effects. Preserve strictness, immutability and cross-field invariants when replacing a hook; do not merely delete it.

Examples

Before — flagged Post-initialization repeats a field contract
app/models.py
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class AudioObject:
generation: int
def __post_init__(self) -> None:
if type(self.generation) is not int or self.generation <= 0:
raise ValueError("generation must be a positive integer")
After — preferred The value field owns strict validation
app/models.py
from typing import Annotated
from pydantic import BaseModel, ConfigDict, Field
class AudioObject(BaseModel):
model_config = ConfigDict(frozen=True)
generation: Annotated[int, Field(strict=True, gt=0)]