Functional options for friendly APIs

https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
webpage banner

Functional options for friendly APIs

This article, based on a presentation by Dave Cheney at dotGo, discusses various API design patterns for creating configurable functions in Go. Cheney critiques common approaches like deeply nested parameters and configuration structs with ambiguous zero values, highlighting their limitations. He then introduces and advocates for the “functional options” pattern, where variadic functions accept other functions to configure an object. This method ensures sensible defaults, high configurability, extensibility, self-documentation, and improved safety by avoiding `nil` parameters. The author demonstrates the practical application of functional options by refactoring his `term` package, illustrating how this pattern leads to cleaner and more expressive APIs.

Note

if you can't make something intuitive, friendly is a good place to land.

it's fascinating how this pattern appears in a lot of go packages but i've definitely seen very little of it in other languages (despite it being possible).

some of it might be due to how Go handles zero values and other language specifics, making this solution more friendly than in other languages. i quite like it though, no matter the language and its quirks (or lack thereof).

Published

2014

Summary

This article, based on a presentation by Dave Cheney at dotGo, discusses various API design patterns for creating configurable functions in Go. Cheney critiques common approaches like deeply nested parameters and configuration structs with ambiguous zero values, highlighting their limitations. He then introduces and advocates for the “functional options” pattern, where variadic functions accept other functions to configure an object. This method ensures sensible defaults, high configurability, extensibility, self-documentation, and improved safety by avoiding `nil` parameters. The author demonstrates the practical application of functional options by refactoring his `term` package, illustrating how this pattern leads to cleaner and more expressive APIs.

Image

Image for Functional options for friendly APIs