PeaBox Lab › PeaLang › Learn › Chapter 7 › Lesson 5

Part II — Intermediate Development · Chapter 7 · Lesson 5 of 7 · 9 min read

Lesson 5: Option, Result, and Future Types

Lesson level: Intermediate

Purpose: Model absence, recoverable failure, and deferred completion explicitly so callers must handle every meaningful outcome.

Learning objectives

By the end of this lesson, you should be able to:

5.1 Three different questions

These types answer different questions:

Do not treat the three as interchangeable wrappers. Their meanings determine how callers branch, propagate, recover, await, test, and report outcomes.

5.2 Option makes absence explicit

An optional lookup should communicate that a valid search may find no value. Conceptually:

function find_employee(id: String) -> Option<Employee>

The caller cannot assume an employee exists merely because the lookup itself completed normally. Presence and absence are both ordinary outcomes.

Use Option when absence is expected and carries no failure detail. Examples include an optional configuration value, a cache miss, a search with no match, or an unassigned owner.

5.3 Presence is not truthiness

An Option containing zero, false, an empty string, or an empty collection is still present. Test the Option state rather than interpreting the contained value by truthiness.

This distinction prevents valid false-like domain values from being mistaken for absence.

5.4 Result separates success from failure

A fallible operation should preserve both its success type and its error type:

function parse_employee(record: Map) -> Result<Employee, ValidationError>

Successful parsing produces an Employee. Expected validation failure produces structured error information. Neither branch needs a magic value such as null, -1, an empty map, or a specially formatted string.

Use Result when callers need to inspect, propagate, transform, retry, aggregate, or report an expected failure.

5.5 Structured handling before access

A caller should establish which variant it has before accessing the contained value or error. Conceptually:

let found = find_employee(employee_id) if found.is_some() {   let employee = found.unwrap()   print employee.name } else {   print "Employee not found" }

The state check justifies access on the guarded path. An unconditional unwrap discards the safety benefit and can fail at runtime.

5.6 Safe defaults

A default is appropriate only when the domain defines a legitimate replacement for absence. A missing display label may use a documented fallback; a missing employee record should not silently become a fabricated employee.

Choose defaults at the consumer, where business meaning is known. Avoid hiding absence inside low-level utilities.

5.7 Transforming Option

A map-like transformation applies a function only when a value is present and preserves absence otherwise.

Conceptually, mapping Option<Employee> through a function Employee -> String yields Option<String>. This avoids repetitive state checks while retaining the possibility of absence.

5.8 Transforming Result

A success transformation changes the successful value and preserves the error. An error transformation changes error representation and preserves success.

For example, a parsed employee can be mapped into an eligibility decision, while a low-level parse error can be mapped into a stable service diagnostic. Keep redaction and public error policy at the boundary where information leaves the subsystem.

5.9 Chaining dependent operations

When the next operation itself returns Option or Result, use a flattening composition pattern rather than creating nested wrappers unnecessarily.

Given:

find_employee(id) -> Option<Employee> find_manager(employee) -> Option<Employee>

A dependent chain should yield Option<Employee>, not Option<Option<Employee>>. The same principle applies to Result-producing validation and persistence steps.

5.10 Propagating errors

A function that cannot recover should preserve or deliberately translate the error rather than catching it and returning a false success.

Propagation keeps the happy path readable and moves recovery to the layer with enough context. Translate errors only when crossing an abstraction boundary, and retain useful cause information without exposing secrets.

5.11 Result versus exceptions

Use Result for expected, typed, inspectable failures that form part of an operation’s contract. Use exceptions for exceptional control transfer, violated assumptions, or failures governed by the language’s exception policy.

The boundary is a design decision. A malformed user record is usually a validation Result; an exhausted runtime budget may be an exception or host-level failure. Do not convert every exception into a generic error value or throw for every expected business rejection.

5.12 Future represents deferred completion

An asynchronous function returns before its eventual value is available. Its contract can expose a Future carrying the completion type.

async function load_employee(id: String) -> Employee

At a call site, the asynchronous invocation conceptually produces Future<Employee>. Awaiting the future suspends cooperatively and resumes with the completed Employee or propagates the operation’s failure according to the asynchronous contract.

5.13 Future does not mean success

A Future describes time, not certainty. Deferred work may succeed, fail, be cancelled, exceed a deadline, or encounter a denied capability. Model the completed outcome precisely.

For expected recoverable failure, a useful contract may conceptually be Future<Result<Employee, LoadError>>. First await completion, then inspect success or error.

5.14 Reading nested types from the outside in

For Future<Result<Option<Employee>, LookupError>>:

Nested types are appropriate only when each layer expresses a distinct domain fact. Simplify redundant layers, but do not collapse meaningful states into ambiguous sentinels.

5.15 Awaiting at the right layer

Keep asynchronous boundaries visible. Await where the caller needs the completed value, and avoid blocking adapters that conceal suspension or deadlines.

After awaiting, handle the resulting Option or Result explicitly. Await does not automatically unwrap absence or recover from a typed error.

5.16 Cancellation and deadlines

Cancellation is not ordinary absence. A cancelled load did not prove that no employee exists. Likewise, a timeout is not an empty result.

Preserve cancellation and deadline semantics through Future boundaries so structured concurrency and host resource governance can stop work predictably. Translate them into a Result only when the public contract intentionally treats them as typed recoverable outcomes.

5.17 Collections of outcomes

A list of Results preserves a per-item outcome; a Result containing a list describes one all-or-nothing operation. These contracts answer different questions:

Choose intentionally and define accounting invariants for inspected, successful, failed, skipped, and cancelled items.

5.18 Portable host boundaries

Option, Result, and Future are internal typed contracts. When crossing a portable host boundary, encode completed outcomes into approved values such as string-keyed maps and lists.

Use stable discriminators such as status or kind, validate both directions, redact sensitive detail, and never attempt to pass a live Future, exception object, host handle, or arbitrary typed object as a portable value.

5.19 Choosing the right contract

SituationPreferred model
Valid lookup may have no matchOption<T>
Expected operation may fail with useful detailResult<T, E>
Value arrives after asynchronous workFuture<T>
Deferred operation may recoverably failFuture<Result<T, E>>
Deferred successful lookup may have no matchFuture<Result<Option<T>, E>>

Use the simplest contract that preserves every meaningful state.

5.20 Outcome diagnostics

Common semantic diagnostics include:

A useful diagnostic identifies the wrapper type, required state or operation, actual use, and the missing handling step.

5.21 Diagnostic workflow

5.22 Common mistakes

5.23 Guided practice

5.24 Hands-on lab: Build a typed employee lookup pipeline

Scenario. Build a typed pipeline that validates a portable request, loads an employee asynchronously, distinguishes no match from provider failure, and returns a portable response.

Requirements

Acceptance criteria. Every outcome is explicit; no sentinel substitutes for absence or failure; no live Future crosses the host boundary; cancellation and deadlines remain distinguishable; portable responses validate; and all semantic and behavior tests pass after deliberate defects are removed.

5.25 Review questions

5.26 Applied challenge

Refactor one earlier checkpoint that uses null, status strings, or exceptions for expected outcomes. Introduce Option for legitimate absence, Result for recoverable failure, and Future only where work is genuinely asynchronous. Provide before-and-after contracts, handling paths, tests for every variant, and a portable boundary mapping.

Lesson summary

Option makes expected absence explicit, Result separates success from recoverable failure, and Future represents deferred completion. Safe programs inspect states before access, transform and chain outcomes without losing meaning, propagate or translate errors deliberately, preserve cancellation and deadlines, distinguish batch-level from per-item outcomes, and convert completed results to validated portable values at host boundaries.

Lesson status: Ready for review.

Next: Chapter 7, Lesson 6 — Flow-Aware Semantic Checks and Type-Checking Commands.

← Previous Next →