Skip to content
Sarj Code Standards

prefer-result-over-nullable-exception

Return a tagged Success | Failure outcome instead of a nullable exception value.

Why

An Error | None return slot encodes success as the absence of a value. Callers must remember an untyped None check, success payloads travel in separate positions, and nothing makes the success and failure cases mutually exclusive.

Fix

Raise the exception, or return a discriminated Success[T] | Failure[E] union (a shared Result alias over two frozen variants) and dispatch on it with match. Keep the failure's typed partial progress inside the Failure variant when callers need it.

Examples

Before — flagged Success is encoded as a missing exception
app/rows.py
class ParsingError(Exception):
pass
def validate(row: dict[str, str]) -> ParsingError | None:
return None if row else ParsingError("empty row")
After — preferred Success and failure are explicit variants
app/rows.py
from dataclasses import dataclass
class ParsingError(Exception):
pass
@dataclass(frozen=True, slots=True)
class Success[T]:
value: T
@dataclass(frozen=True, slots=True)
class Failure[E: BaseException]:
error: E
type Result[T, E: BaseException] = Success[T] | Failure[E]
def validate(row: dict[str, str]) -> Result[dict[str, str], ParsingError]:
return Success(row) if row else Failure(ParsingError("empty row"))