Diseño Funcional
Modelado FP
Escrito por Darjus Kazakevic · revisado el
Pure functions in the middle, side effects at the edges.
Functional design separates deciding from doing. The core is pure functions: the same input always gives the same output, and nothing reads the clock or the database. Side effects (reads, writes, network calls) live in a thin shell around that core. This shape is often called “functional core, imperative shell”.
Types do the job that private fields do in object-oriented design. A Percent type that cannot hold 200 is checked once, at the boundary, not in every function. The costs: the style is new to many teams, and copying immutable data uses memory and time. Measure that cost before you worry about it.
En esencia — Keep the core pure and the data immutable, and push every side effect to a thin shell at the edge.
Cuándo recurrir a él
Recurre a él cuando
- Business logic you want to test by calling it, with no mocks
- Rules you can encode once as a type instead of checking everywhere
- Data pipelines: parse, transform, validate, then write
Reconsidéralo cuando
- A team new to the style, on a deadline with no time to learn it
- A measured hot path where copying immutable data shows up in profiles
- Code that is mostly I/O, with almost no logic to keep pure
Conceptos clave
- Pure function
- A function whose result depends only on its arguments, and which changes nothing outside itself. You test it by calling it with a literal and checking the result.
- Immutable data
- Values are never changed in place. An update returns a new value, so no other code ever sees a half-finished change.
- Functional core, imperative shell
- The pure logic sits in the middle. A thin outer layer reads the inputs, calls the core, and writes the results. Gary Bernhardt made the name popular.
- Make illegal states unrepresentable
- Design types so that an invalid value cannot exist. Use branded types for checked numbers and union types for states, so the compiler rejects mistakes.
Reglas de diseño
- Decide in the core, act at the edge
- Keep the core free of I/O: no clock, no database, no random numbers. Read inputs and write results in a thin shell around it. Then you test most logic by calling it.
- Check once at the boundary, into a type
- Parse raw input into a type that cannot hold an invalid value, such as a Percent that rejects 200. Code inside the core then never repeats the check.
- Pass time and randomness in as arguments
- A function that calls Date.now() or Math.random() is not pure. Take now or a seed as a parameter, and tests become exact instead of flaky.
Errores habituales
- A “pure” function that calls Date.now() inside. Tests pass today and fail at midnight.
- Side effects creep back into the core through a logger or a global config. The core needs mocks again.
- Long point-free pipelines that only their author can read.
- Copying a large array on every small update inside a hot loop, then blaming the style for the slowdown.