Skip to content
Sarj Code Standards

prefer-match-value-dispatch

Prefer match/case for repeated dispatch on one value with a fallback.

Why

A single dispatch subject makes distinct value cases and their fallback easier to review.

Fix

Consider match/case while preserving fallback and constant semantics; use literal or dotted value patterns, never bare constant names that capture instead of compare. Review membership versus equality, subject evaluation, and guard order before rewriting.

Examples

Before — flagged An implicit format group hides future values
app/formats.py
from typing import Literal
Format = Literal["pcm", "wav", "mp3", "flac"]
def encode(value: Format):
if value in ("pcm", "wav"):
return direct(value)
return compressed(value)
After — preferred Every format belongs to an explicit case
app/formats.py
from typing import Literal
Format = Literal["pcm", "wav", "mp3", "flac"]
def encode(value: Format):
match value:
case "pcm" | "wav":
return direct(value)
case "mp3" | "flac":
return compressed(value)
Before — flagged Dispatch a stable parameter through literal cases
app/parse.py
def parse(kind):
if kind == "json":
return json_parser()
elif kind == "yaml":
return yaml_parser()
else:
return fallback()
pyproject.toml
[project]
requires-python = ">=3.10"
After — preferred Use value cases and retain the fallback
app/migrate.py
def migrate(path):
match path.name:
case "eslint.json":
return rewrite_eslint(path)
case "ratchet.json":
return rewrite_ratchet(path)
case _:
return rewrite(path)
Before — flagged Keep error variants and their fallback under one dispatch subject
app/errors.py
from provider import ErrorId
def classify(error_id):
if error_id == ErrorId.INSUFFICIENT:
return insufficient()
if error_id == ErrorId.INVALID_OPTION:
return invalid_option()
return rejected()
pyproject.toml
[project]
requires-python = ">=3.10"
After — preferred Value cases preserve the terminal fallback
app/errors.py
from provider import ErrorId
def classify(error_id):
match error_id:
case ErrorId.INSUFFICIENT:
return insufficient()
case ErrorId.INVALID_OPTION:
return invalid_option()
case _:
return rejected()