Library Design: Naming Conventions
Part 3: Option & Result
Published on 2024-07-05. Last updated on 2025-08-02
Many languages’ Option and Result types suffer from an organically-grown and therefore inconsistently named set of functions.
To avoid this, a simple naming scheme can be used to derive a full set of useful methods with predictable names for these types.
The examples below use variant names Some and None for Option, and variant names Pass and Fail for Result.1
Naming Scheme
Given a function operating on Option[T] or Result[T, E] …
getindicates a result type ofT,
its lack indicates a result type ofOption[T]/Result[T, E]elseindicates a closure argument,
its lack indicates an eagerly evaluated value...Panicindicates a possibly panicking function,
its lack indicates a total function- additional combinator function names are adopted from Naming Conventions – Streaming as appropriate
where...Noneor...Failvariants indicate working on the error value instead of on the success value
| Function Name | Code Example |
|---|---|
or |
Some(1).or(Some(2)) --> Some(1) None.or(Some(2)) --> Some(2) Pass(1).or(Pass(2)) --> Pass(1) Fail(1).or(Pass(2)) --> Pass(2) |
orElse |
Some(1).orElse(() -> Some(2)) --> Some(1) None.orElse(() -> Some(2)) --> Some(2) None.orElse(() -> None) --> None Pass(1).orElse(() -> Pass(2)) --> Pass(1) Fail(1).orElse(() -> Pass(2)) --> Pass(2) |
getOr |
Some(1).getOr(2) --> 1 None.getOr(2) --> 2 Pass(1).getOr(2) --> 1 Fail(1).getOr(2) --> 2 |
getOrElse |
Some(1).getOrElse(() -> 2) --> 1 None.getOrElse(() -> 2) --> 2 Pass(1).getOrElse(() -> 2) --> 1 Fail(1).getOrElse(() -> 2) --> 2 |
getOrPanic |
Some(1).getOrPanic() --> 1 None.getOrPanic() # program aborts Pass(1).getOrPanic() --> 1 Fail(1).getOrPanic() # program aborts |
getOrPanicWith |
Some(1).getOrPanicWith("expected some") --> 1 None.getOrPanicWith("expected some") # program aborts with message "expected some" Pass(1).getOrPanicWith("expected some") --> 1 Fail(1).getOrPanicWith("expected pass") # program aborts with message "expected pass" |
-
Having variant names with the same length avoids pointless debates and diverging code style decisions on whether the arms of matches should be lined up or not. ↩