Designing a module's API
45. Put the data first
Section titled “45. Put the data first”A function takes the value it works on as its first parameter, so a caller can pipe into it (§7): Map.get(m, k), String.trim(s), Iter.map(xs, f). Options and callbacks come after it.
HTTP middleware follows the rule: the handler is the value it works on, so it comes first, and the middleware returns a handler, fn require_admin(handler: Handler) -> (Request) -> Response. A stack of middleware is then a pipe. A middleware that hands the handler a value, such as the signed-in user, says so in the handler’s type, (Request, User) -> ToResponse, rather than storing it on the request, so a route that needs a user cannot be registered without the middleware that finds one.
46. Name conversions and locale functions by their shape
Section titled “46. Name conversions and locale functions by their shape”A conversion from one value type to another is to_<target> on the source type: Int.to_float, Int.to_decimal, Float.to_int, String.to_int, String.to_decimal, Int.to_codepoint. from_ is for building a value out of its units, an encoding or a collection, on the type it builds: Instant.from_seconds, Uuid.from_bytes, Int.from_digits, String.from_codepoints, Bytes.from_list. A function that returns a value of the type it takes is named for what it does, with no to_: String.trim, String.uppercase, String.fold_case, String.snake_case. A conversion interface sits on the target type, impl From<sql.Error> for ApiError, because the orphan rule puts it there: impl To<ApiError> for sql.Error would put the local type in a type parameter only a result names, while From’s E is an input, so impl From<LocalErr> for ForeignErr is allowed (spec §12 Foreign Types).
A function that reads or changes text by a locale’s conventions ends in _in when its name without the suffix is, or would be, the same operation by no locale’s conventions: Date.parse reads ISO 8601 (2024-03-15) and Date.parse_in a reader’s (15.03.24 in de), and Int.parse_in is to String.to_int what Date.parse_in is to Date.parse; String.uppercase is Unicode’s default casing and String.uppercase_in the locale’s; Money.parse_in reads what Money.format writes, beside the 12.50 EUR its Display writes. A function that only means something in a locale takes one with no suffix: every format and format_* (a value’s text in no locale is its Display, not a format), String.join_list, PluralCategory.cardinal and Collator.new. Either way the locale is the second parameter, after the value the function reads or writes, and before the options: Decimal.parse_in(text, locale, lenient: True), TimeUnit.format_relative(3, locale, TimeUnit.Day). Std follows the rule, and a library that formats for a reader should too.
47. Make a type opaque to keep an invariant
Section titled “47. Make a type opaque to keep an invariant”When only some values of a representation are valid (a clock’s minutes within one day, a fraction in lowest terms, a queen on the board), declare the type pub opaque (spec §4 Opaque distinct types; tour: Modules & Imports) and build it only through functions that establish the rule. Code outside the file cannot build or take apart the value, so every value it holds obeys the rule, and nothing downstream checks it again:
pub opaque type Clock Int impl Clock pub fn new(hour: Int, minute: Int) -> Clock Clock(Int.modulo(hour * 60 + minute, 1_440)) end end
Keep the representation canonical, one value for each thing it stands for, and a derived Equatable is the right equality: two clocks that show the same time hold the same Int. A constructor that can refuse its input returns a Result (Queen.new(row, column)), since the caller may not know the input is bad (§29). Give the type the accessors its users need (§18). A type with no rule to keep stays transparent: opaque on it only hides fields callers would read. An opaque type inspects as <opaque Clock>, and derive Debug shows its value; a type with secret fields writes an impl Debug that leaves them out instead.
When the rule is a test of one value that callers should go on using as the type it narrows (a port number, a divisor that is not zero, a tolerance that is not negative), declare a subtype instead (spec §4 Subtypes; tour: Structs, Enums & Distinct Types). A parameter typed with the subtype replaces a check that traps or a Result the function returns only for that argument: a literal argument is checked when the program compiles, and a computed one goes through try_from where it is made, once:
pub subtype Port Int when fn p -> p >= 1 and p <= 65535 pub fn listen(port: Port) -> String "listening on ${port}" end
Std’s equal_within takes a NonNegativeFloat tolerance, Int.pow a NonNegativeInt exponent and Money.split a PositiveInt count this way. Reach for the prelude’s subtypes (NonNegativeInt, PositiveFloat, NonEmptyString and the rest) before declaring one, and name a subtype’s existing parents with and rather than repeating their rules; a parameter that needs two of them takes NonNegativeInt and NonZeroInt rather than a new subtype for one function. When the value is a thing of its own that callers must not mix with other values of its base (an email address, a user id), declare a validated type, type Email String when is_email or type UserId PositiveInt, which converts to nothing. Keep opaque for a rule over a representation callers should not see, or one a single value cannot be tested for alone.
A function that has no answer for an empty collection takes the prelude’s NonEmptyList (or NonEmptyVector, NonEmptyMap, NonEmptySet) and returns its answer, rather than taking a List and returning a Maybe that every caller who already knows the list has elements must unwrap. Return a Maybe when emptiness comes from data the caller does not control, as Iter.first on any iterable does. A caller holding a List checks it once, with NonEmptyList.try_from, where the list is made:
fn average(xs: NonEmptyList<Float>) -> Float Iter.sum(xs) / Int.to_float(NonEmptyList.length(xs)) end
48. Give a module’s errors an enum
Section titled “48. Give a module’s errors an enum”A module whose functions can fail in more than one way declares an error enum (spec §11 Error types), named Error (§4), with a variant per way, and its functions return Result<T, Error>. A caller matches the variant, tests compare variants rather than message text, and a case over the error is checked for every way. A Display impl gives the message a person reads:
pub enum Error TooShort AreaCodeStartsWithZero end impl Display for Error fn to_string(error: Error) -> String case error .TooShort -> "must not be fewer than 10 digits" .AreaCodeStartsWithZero -> "area code cannot start with zero" end end end
not Result<String, String>, whose callers can only compare text. Keep a String error for a failure only a person reads: a script’s, or a boot that only reports why it stopped (§38). A variant carries the data its message needs (InvalidDigit Int), not the message.
An HTTP app’s error enum implements std::http’s ToResponse as well, so a handler returns Result<Response, AppError> and passes failures up with ? rather than turning each one into a page where it happens.
49. Doc comments and examples
Section titled “49. Doc comments and examples”Put a /// doc comment (spec §2 Comments) on every pub declaration, and show its use with //! attached tests (spec §17 Attached tests; tour: Testing). nomi test runs them, and the stdlib reference renders them as runnable examples, so an example that goes stale fails. The stdlib does this throughout (std/sets.nomi, std/iter.nomi):
impl Set<T> /// Returns a new set with `elem` added (no-op if already present). //! assert Set.insert([1, 2], 3) == [1, 2, 3] //! assert Set.insert([1, 2], 2) == [1, 2] // pub fn insert<T>(s: Set<T>, elem: T) -> Set<T> Set{items: Map.put(s.items, elem, True)} end end
When an attached assertion’s subject becomes multi-line, keep the assertion at the front and prompt each continuation line:
//! assert Iter.loop(0, fn n -> //! if n >= 3 then //! break n //! else //! n + 1 //! end //! end) == 3
When a compact example needs setup, write the setup as ordinary prompted lines:
//! v: Vector<Int> = [] //! assert Vector.length(v) == 0
Keep a fenced ```nomi block inside /// for code that is not an assertion, such as how to implement an interface (Iter’s doc comment shows a custom each_while). Nothing checks those blocks, so prefer //! whenever an assertion can show the point.
Describe a whole file with //# lines at its top, in every file, not only in std/. A test file may leave it out: its name says which file it tests, and its tests’ names say what they check. Use //# rather than a plain // above the first declaration, which reads as that declaration’s comment.
//# Parses and evaluates the word problems of the exercise. /// Answers a word problem. pub fn answer(question: String) -> Result<Int, Error> ... end
50. Write generated code a reader can trust
Section titled “50. Write generated code a reader can trust”These rules are for the author of a tool that generates Nomi code (nomi tool), such as sqlkit’s generate (tour: Generating Code).
- Write files
nomi fmtleaves alone. A reader reviews generated code in a diff, and a formatter pass that rewrites it every time hides the change that matters. Lay the code out as the formatter does. - Say what made the file. Start each file with a comment that names the tool and its inputs and says not to edit it, and record a checksum of the inputs there:
// inputs sha256: .... - Fail before writing. Check the inputs first, report each problem at its file and line,
db/queries/users.sql:12:5: ..., and write nothing when there is one, so a half-written set of files never reaches the checker. - Offer
--checkand a test.--checkwrites nothing and fails when a file is not what the tool would write, for an automated check. A generated test that computes the inputs’ checksum again and compares it with the header’s makes a plainnomi testnotice a forgotten run.
51. Acquire a resource, then defer its release on the next line
Section titled “51. Acquire a resource, then defer its release on the next line”std offers no scoped with_* form that runs a function with a resource. A function acquires the resource, defers its release on the next line, and uses it in the same body, so the release runs however the function ends: by its last line, a return, a ? or a trap. A writer’s success path closes it with ?, which commits the write and reports a failed close; the deferred Writer.discard throws the output away on every other way out.
fn save(path: String, rows: List<String>) -> Result<Unit, io.Error> w = fs.create(path, mode: .ReplaceAtomically)? defer Writer.discard(w) Writer.write_lines(w, rows)? Writer.close(w)? Ok(Unit) end
The other pairs: fs.open and Reader.close_quietly, fs.open_file and File.close_quietly, fs.make_temp_dir and fs.remove_all_quietly, process.spawn and Child.kill, http.stream and StreamedResponse.close, and a driver’s open and sql.close_quietly.
The checker holds the rule for a type that implements Release, and the success path’s close for one that implements Commit (spec §9 Releasing resources). A type of your own that holds something to give back implements Release, with the body of its release calling the function a caller defers.
52. Take an interface value unless the caller’s type comes back
Section titled “52. Take an interface value unless the caller’s type comes back”A parameter used only through one interface, whose type appears nowhere else in the signature, takes the interface as its type. It reads as what it is, any value that can do this:
fn text(error: Display) -> String "failed: ${error}" end
Write a type parameter when the caller’s type matters past the call: it recurs in another parameter, in the result or inside another type (Result<T, E>, a returned (E) -> Error), it needs two bounds, or the body calls an interface function whose result is self or that takes no self. An interface value keeps none of that (spec §12 Interface values):
fn larger<T>(a: T, b: T) -> T where T: Comparable if a > b then a else b end
A function taking an interface value passes where a function of the concrete type is expected, so Result.map_err(text) works on any error that implements Display (spec §5 Assignability). A struct or an enum of your own enters its interface unboxed, so the two forms cost the same.
nomi check and the editor suggest this rewrite, with a fix, for a type parameter used once as a parameter’s type under one bound.