Basic dependency injection in OCaml with objects
6 days ago
- #OCaml
- #Functional Programming
- #Dependency Injection
- The article discusses dependency injection in OCaml, comparing two approaches: using user-defined effects and modules as first-class values.
- It highlights ergonomic weaknesses in both approaches and proposes a new encoding using OCaml's object model for dependency injection.
- Dependency injection is praised for simplifying unit testing, as demonstrated by the author's time-tracker project, Kohai.
- The article explores the drawbacks of using modules for dependency injection, such as verbosity and limited type inference.
- User-defined effects are critiqued for being cumbersome without a type system to track effects, making them less suitable for dependency injection.
- The author advocates for using OCaml's objects for dependency injection, citing structural subtyping and type inference as advantages.
- A practical example demonstrates how objects can be used to handle dependencies in a teletype application, showcasing compositionality and type safety.
- The article introduces a module named 'Env' to manage dependencies more cleanly, inspired by the Reader monad, to avoid bloating business logic code.
- It concludes by emphasizing the power of OCaml's object model for dependency injection, offering static tracking of dependencies and ease of testing.
- Future possibilities include using Modular Implicits for lighter handler provision, and the article acknowledges contributions from peers in the OCaml community.