Skip to content
Sarj Code Standards

prefer-required-constructor-parameters

Prefer required constructor parameters so callers choose dependencies and configuration explicitly.

Why

Defaulted constructor parameters hide choices at the composition boundary. Replacing None with an empty string, a constant, or a factory still permits an implicit choice. A required nullable parameter makes a meaningful absent value explicit without inventing a sentinel. None is not meaningful when the constructor immediately replaces it with a constructed fallback, or when it stands for a disabled service that every consumer must re-check instead of receiving a disabled implementation.

Fix

Require the parameter and update callers to pass their choice explicitly; preserve meaningful None values. Pass the fallback from the composition root, and model a disabled service as an implementation of its interface. Suppress intentional framework or public-library defaults with a compatibility reason.

Examples

Before — flagged Constructor silently selects an empty configuration
app/service.py
class Service:
def __init__(self, agent_name: str = "") -> None:
self.agent_name = agent_name
After — preferred Caller explicitly chooses an absent configuration
app/service.py
class Service:
def __init__(self, agent_name: str | None) -> None:
self.agent_name = agent_name
Before — flagged Constructor accepts None only to build its own dependency
app/service.py
class Service:
def __init__(self, timing: Timing | None) -> None:
self.timing = timing or Timing()
After — preferred None selects a value derived from the runtime
app/service.py
import os
class Service:
def __init__(self, workers: int | None) -> None:
self.workers = workers or os.cpu_count()

Formerly: discourage-nullable-constructor-parameters