
jvelilla
Advanced Functional Programming with Elixir: B4.0
Chapter One makes a reference to DDD to use factories
In Domain-Driven Design, a factory creates domain objects in a consistent
way, keeping their internal structure loosely coupled from the rest of the
system. The FunPark.Ride module follows this pattern by exposing a make/2 factory
function for creating new rides.
I understand the idea that each module uses factories to maintain a consistent creation, but the current approach could create domain object that have invalid values.
Some factories in FunPark (chapter 1) enforce required arguments, but optional arguments are just passed without validation. We can accidentally pass an invalid value and the struct will happily accept it.
For example:
dark_mansion2 = FunPark.Ride.make(
“Dark Mansion”,
min_age: -10,
tags: [:dark]
)
Maybe the factory should only accept required fields.
- Optional fields are updated with dedicated function (check preconditions)
I guess this kind of validations will be treated in other sections of the book.
def make(name, opts \\ []) when is_binary(name) do
%__MODULE__{
id: :erlang.unique_integer([:positive]),
name: name
}
end
Example check precondition
def set_min_age(%__MODULE__{} = ride, age) when is_integer(age) and age >= 0 do
{:ok, %{ride | min_age: age }}
end
def set_min_age(_, _
) do
{ :error, invalid_age }
end
This is very close to design by contract style in Eiffel.
Popular Pragmatic Bookshelf topics










Other popular topics










Categories:
Sub Categories:
Popular Portals
- /elixir
- /rust
- /ruby
- /wasm
- /erlang
- /phoenix
- /keyboards
- /rails
- /python
- /js
- /security
- /go
- /swift
- /vim
- /clojure
- /emacs
- /haskell
- /java
- /onivim
- /typescript
- /svelte
- /kotlin
- /crystal
- /c-plus-plus
- /tailwind
- /react
- /gleam
- /ocaml
- /elm
- /flutter
- /vscode
- /ash
- /html
- /opensuse
- /centos
- /php
- /deepseek
- /zig
- /scala
- /sublime-text
- /lisp
- /textmate
- /nixos
- /debian
- /react-native
- /agda
- /kubuntu
- /arch-linux
- /django
- /revery
- /ubuntu
- /spring
- /manjaro
- /nodejs
- /diversity
- /deno
- /lua
- /julia
- /slackware
- /c