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:
- distinguish absence, failure, and deferred completion;
- choose Option instead of an ambiguous null sentinel;
- choose Result instead of mixing success values with errors;
- understand Future as a typed deferred outcome;
- inspect, transform, and compose these generic types;
- avoid unsafe unwrapping;
- convert host and external outcomes at trusted boundaries;
- read nested outcome types; and
- diagnose incomplete or incompatible handling.
5.1 Three different questions
These types answer different questions:
- Option<T>: Is a value present?
- Result<T, E>: Did an operation succeed, or did it produce a recoverable error?
- Future<T>: Will a value become available after asynchronous work completes?
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>>:
- Future: completion is deferred.
- Result: the completed operation may succeed or produce LookupError.
- Option: a successful lookup may still find no employee.
- Employee: when present, this is the value type.
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:
- List<Result<Employee, Error>> supports partial batch success.
- Result<List<Employee>, Error> represents one batch-level success or failure.
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
| Situation | Preferred model |
|---|---|
| Valid lookup may have no match | Option<T> |
| Expected operation may fail with useful detail | Result<T, E> |
| Value arrives after asynchronous work | Future<T> |
| Deferred operation may recoverably fail | Future<Result<T, E>> |
| Deferred successful lookup may have no match | Future<Result<Option<T>, E>> |
Use the simplest contract that preserves every meaningful state.
5.20 Outcome diagnostics
Common semantic diagnostics include:
- accessing an Option value without proving presence;
- using a Result as though it were its success value;
- returning T where Option<T> is required, or the reverse;
- incompatible success or error transformations;
- forgetting to await a Future before using its completed value;
- awaiting a non-Future value;
- incompatible branches after outcome inspection;
- dropping an error or cancellation path; and
- attempting to export a non-portable live outcome.
A useful diagnostic identifies the wrapper type, required state or operation, actual use, and the missing handling step.
5.21 Diagnostic workflow
- Write the complete type, including every nested layer.
- Read it from the outside inward.
- Identify which state is currently proven.
- Determine whether the code needs inspection, mapping, chaining, propagation, awaiting, or conversion.
- Handle every meaningful variant.
- Keep runtime validation and resource controls intact.
- Run semantic checks and focused tests.
5.22 Common mistakes
- Using null for every absence. Prefer Option when absence is part of the contract.
- Using false, -1, or an empty map as failure. Prefer Result with structured error information.
- Unwrapping without a proof. Inspect or propagate first.
- Inventing a default. Defaults must have domain meaning.
- Confusing absence with failure. No match differs from a failed lookup.
- Confusing timeout with absence. Preserve operational failure semantics.
- Forgetting that Future may fail. Deferred work is not guaranteed success.
- Creating unnecessary nested wrappers. Flatten dependent compositions.
- Dropping error context. Translate deliberately and redact at boundaries.
- Exporting internal wrappers directly. Convert completed outcomes to portable values.
5.23 Guided practice
- Choose Option or Result for a cache miss, malformed record, and denied permission.
- Explain why Some(false) is present.
- Replace a -1 error sentinel with a typed Result contract.
- Map Option<Employee> into an optional employee name.
- Chain two Result-producing validation steps without nesting Results.
- Read Future<Result<Option<Map>, Error>> from outside inward.
- Decide whether cancellation belongs in the error type or remains an asynchronous control outcome.
- Choose between a list of Results and a Result containing a list.
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
- Validate employee_id and request metadata at the boundary.
- Model validation with Result.
- Model a successful lookup with no employee using Option.
- Model deferred provider work using Future.
- Use a combined contract that preserves failure and absence distinctly.
- Apply a deadline and propagate cancellation correctly.
- Transform a present employee into a typed summary.
- Map internal errors to stable redacted service errors.
- Encode completed outcomes as portable maps with stable discriminators.
- Test success, no match, invalid request, provider error, timeout, cancellation, and malformed provider output.
- Introduce unsafe unwrap, missing await, and incompatible mapping defects; record diagnostics.
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
- What distinct questions do Option, Result, and Future answer?
- Why is Some(0) different from absence?
- When is a default value appropriate for Option?
- Why is Result clearer than a magic error sentinel?
- How do success mapping and error mapping differ?
- Why should dependent operations flatten nested outcome types?
- When should an expected failure use Result rather than an exception?
- Why does a Future not guarantee success?
- How do cancellation and timeout differ from no result?
- What is the difference between List<Result<T,E>> and Result<List<T>,E>?
- Why must completed outcomes be converted before crossing a portable host boundary?
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.