Error handling should use Result-style semantics.
import fs
data DocSource {
path: Str
content: Str
}
def load_doc(path: Str) -> Result[DocSource, Str] {
if not fs.exists(fs.path(path)) {
return Err("file not found: " + path)
}
let rp = fs.read_path(path).unwrap()
return Ok(DocSource(path, fs.read_text(rp).unwrap()))
}
Usage:
def process_doc(path: Str) -> Result[Str, Str] {
let doc = load_doc(path) ?else return Err("invalid document")
return Ok(doc.content)
}
Errors become explicit branches that tests can evaluate.
Contracts describe meaningful invariants.
data DocPage {
slug: Str
title: Str
category: Str
order: Int
}
def parse_doc(md: Str) -> DocPage {
in {
len(md) > 0
}
out (result) {
result.slug != ""
}
return DocPage("intro", "Introduction", "docs", 1)
}
Contracts provide validation, documentation, and automatic verification. A mutant that violates a contract is killed without a dedicated test. See Contracts for syntax and Contracts in mutation for how they interact with mutation testing.
Side effects should be limited to small execution layers.
Common effects: filesystem, subprocess, HTTP server, logging.
data DeployPlan {
target: Str
source_dir: Str
}
data DeployReport {
success: Bool
files_copied: Int
}
def plan_deploy(target: Str) -> DeployPlan {
return DeployPlan(target, "build/")
}
def run_deploy(plan: DeployPlan) -> DeployReport {
return DeployReport(True, 0)
}
Effects should be thin shells around pure decisions.
Use defer to control resource cleanup.
import process
import fs
def cleanup_example() {
let dir = process.tempdir() + "/work"
fs.mkdir(fs.path(dir))
defer { fs.remove_dir(fs.path(dir)).unwrap() }
}
This ensures predictable cleanup and reduces hidden state.
Use enums for closed decision sets.
enum PageKind {
Doc
Blog
Landing
Error
}
pure def page_template(kind: PageKind) -> Str {
match kind {
case PageKind.Doc { return "doc.html" }
case PageKind.Blog { return "blog.html" }
case PageKind.Landing { return "index.html" }
case PageKind.Error { return "404.html" }
}
}
Finite decision spaces allow mutation testing to exhaustively explore logic. When a match expression covers every variant, a mutant that swaps one branch for another is detectable.
Use expression forms when appropriate.
def pick_title(title: Str?, slug: Str) -> Str {
let result = if title is not None { title } else { slug }
return result
}
Expression-oriented code reduces procedural scaffolding.
Primary constructors should validate object state.
class ValidatedPage(slug: Str, title: Str) {
init {
if slug == "" { raise ValueError("empty slug") }
}
}
This ensures invalid states cannot exist.
Interfaces encapsulate external dependencies.
interface FileSystem {
def read(self, path: Str) -> Str {
}
def write(self, path: Str, content: Str) {
}
}
External volatility stays outside core logic. See HTTP services for how interfaces map to service endpoints.