|
| 1 | +# Effect-TS Best Practices (concise) |
| 2 | + |
| 3 | +## Design principles |
| 4 | + |
| 5 | +- Keep core logic pure; isolate IO in a thin shell. |
| 6 | +- Model errors explicitly with tagged unions; avoid exceptions. |
| 7 | +- Prefer immutable data and total functions. |
| 8 | + |
| 9 | +## Composition |
| 10 | + |
| 11 | +- Use pipe + Effect.flatMap/map or Effect.gen for sequential flows. |
| 12 | +- Interop with Promise only at boundaries via Effect.try/Effect.tryPromise. |
| 13 | +- Use Match.exhaustive for union handling; avoid switch in domain logic. |
| 14 | + |
| 15 | +## Dependency injection |
| 16 | + |
| 17 | +- Define services with Context.Tag and small interfaces. |
| 18 | +- Provide live layers at runtime; provide test layers in unit tests. |
| 19 | +- Keep service interfaces free of concrete implementations and globals. |
| 20 | + |
| 21 | +## Boundary validation |
| 22 | + |
| 23 | +- Accept unknown at the boundary only. |
| 24 | +- Decode with @effect/schema and pass validated types into core. |
| 25 | +- Fail fast on invalid input; keep validation errors typed. |
| 26 | + |
| 27 | +## Resource safety |
| 28 | + |
| 29 | +- Use Effect.acquireRelease for resources (connections, files, locks). |
| 30 | +- Use Effect.scoped to control lifetimes and ensure finalizers run. |
| 31 | + |
| 32 | +## Platform usage |
| 33 | + |
| 34 | +- Use @effect/platform services instead of host APIs: |
| 35 | + - HttpClient/HttpServer for HTTP |
| 36 | + - FileSystem/Path for files and paths |
| 37 | + - Command/Terminal for CLI and processes |
| 38 | + - KeyValueStore for local storage-like needs |
| 39 | + |
| 40 | +## Runtime and entrypoints |
| 41 | + |
| 42 | +- Use Effect.runMain (or platform runtime helpers) for application entry. |
| 43 | +- Use Logger/PlatformLogger for structured logging. |
| 44 | + |
| 45 | +## Testing |
| 46 | + |
| 47 | +- Write tests as Effects; provide test layers/mocks. |
| 48 | +- Use TestClock/Ref for deterministic time and state. |
| 49 | +- Use property-based tests for invariants when appropriate. |
| 50 | + |
| 51 | +## Minimal example (service + layer) |
| 52 | + |
| 53 | +```ts |
| 54 | +import { Context, Effect, Layer, pipe } from "effect" |
| 55 | + |
| 56 | +class Clock extends Context.Tag("Clock")<Clock, { |
| 57 | + readonly nowMillis: Effect.Effect<number, never> |
| 58 | +}>() {} |
| 59 | + |
| 60 | +const ClockLive = Layer.succeed(Clock, { |
| 61 | + nowMillis: Effect.sync(() => Date.now()) |
| 62 | +}) |
| 63 | + |
| 64 | +const program = pipe( |
| 65 | + Clock, |
| 66 | + Effect.flatMap((clock) => clock.nowMillis), |
| 67 | + Effect.map((ms) => ({ now: ms })) |
| 68 | +) |
| 69 | + |
| 70 | +const main = Effect.provide(program, ClockLive) |
| 71 | +``` |
0 commit comments