Skip to content
Sarj Code Standards

prefer-outcome-variants

Represent distinct outcomes with named variants.

Why

An optional error beside success state admits contradictory combinations. A bare scalar or None in a result union also lets a caller return an unrelated value of the same type. Named variants make each decision explicit.

Fix

Use a payload class for success and a fieldless class for a distinct empty outcome. Match on their classes and the existing failure type. For serialized records, retain the established Result or shared Literal discriminator and preserve the wire contract.

Examples

Before — flagged A result uses bare bytes and None for two outcomes
app/reader.py
from enum import Enum
class ReadFailure(Enum):
CLOSED = 1
type ReadResult = bytes | ReadFailure | None
def read() -> ReadResult:
return None
After — preferred A chunk, end of stream and failure each have a distinct type
app/reader.py
from dataclasses import dataclass
from enum import Enum
class ReadFailure(Enum):
CLOSED = 1
@dataclass(frozen=True)
class Chunk:
data: bytes
@dataclass(frozen=True)
class EndOfStream:
pass
type ReadResult = Chunk | ReadFailure | EndOfStream
def read() -> ReadResult:
return EndOfStream()
Before — flagged A nullable error and success flag admit contradictory outcomes
app/models.py
from pydantic import BaseModel
class AudioResult(BaseModel):
passed: bool = False
error: str | None = None
value: bytes | None = None
After — preferred Success and error variants have non-null payloads
app/models.py
from typing import Literal
from pydantic import BaseModel
class RunSuccess(BaseModel):
passed: Literal[True] = True
value: bytes
class RunError(BaseModel):
passed: Literal[False] = False
error: str
type RunResult = RunSuccess | RunError