Skip to content

Latest commit

 

History

History
executable file
·
29 lines (15 loc) · 1.96 KB

adr-008.md

File metadata and controls

executable file
·
29 lines (15 loc) · 1.96 KB

ADR 8: Use Option<T> to model optional values

Context

Many computations may return a value, or no value at all. Classical examples include finding an element in a collection, or finding the value associated to a key in a keyed collection. More domain specific examples include finding the cascaded value of a CSS property, the role or the accessible name of an element, …

ES traditionally model these with the use of either the null or undefined values. To prevent runtime errors, non-null checks must then be introduced in many places (type safety can still be ensured). The many non-null checks can often be alleviated by used of optional chaining (?.) and nullish coalescence (??). While these work well enough for methods chaining, they are not usable when chaining functions.

Functional Programming languages often have an Option type to represent these values.

Decision

We will implement an Option<T> type and use it to model optional results. We will avoid the use of null or undefined to represent non-existent value as much as possible (they are still needed, for example, to represent optional parameters to a function since this is ES way of handling them).

The Option<T> type will be implemented as a monad to allow easy chaining of operations on the contained value and remove the need for constantly checking whether it exists.

Status

Accepted.

Consequences

The Option<T> type provides better type safety and makes it obvious in signatures that the value may be absent.

The monadic implementation, and use of map and flatMap helpers makes the machinery of checking presence transparent to callers and offer a cleaner API.

The resulting code style is closer to Functional Programming languages, which may be unsettling for developers not used to them; but may also ease entry cost for developers used to them…

See more discussion about this choice in "The great refactoring" pull request.