Categorias
Programming Technology

The Principle Is Not the Mechanism: ISP, DIP, and Language Structures in Practice

A small refactor made me think: how many times do we mix a principle with mechanisms? For example, Interface Segregation and Dependency Inversion are many times seen naturally in OOP, but they are principles and they survive a change of paradigm. TypeScript is this interesting case: it supports both OOP and functional styles in the same codebase, and both can preserve the I and D from SOLID. This article separates the principles from the mechanisms that carry them, maps how OOP and functional TypeScript preserve the same design responsibilities. And it proposes yet another comparison of things that look tied together, but are separate concepts in the language structures underneath: where structural typing and duck typing share a philosophy but diverge in practice.

Contents

  1. The in-memory repository that made the mapping visible
  2. Preserve the responsibilities, change the mechanisms
  3. Map responsibilities, not syntax
  4. Service factories, closures, and composition
  5. Structural typing: the conformance mechanism
  6. Testing: where duck typing walks back in
  7. Untangling the five concepts
  8. The language field guide
  9. A good way to use them
  10. The honest counterpoint
  11. Checklist
  12. Recap

Obs.: Check the Glossary at the end if you need clarification on concepts I am using in the article.

The in-memory repository that made the mapping visible

In a production TypeScript API I work on, the persistence design was still evolving while the Use Cases needed to move forward. We deliberately introduced an in-memory implementation of the domain contract:

// infrastructure/repository/in-memory.user.repository.ts
import { randomUUID } from 'node:crypto';
import type { NewUser, User, UserRepository } from '../../domain/user';

const usersByDocument = new Map<string, User>();

async function findByDocument(document: string): Promise<User | null> {
  return usersByDocument.get(document) ?? null;
}

async function create(data: NewUser): Promise<User> {
  const user: User = { id: randomUUID(), ...data, createdAt: new Date() };
  usersByDocument.set(data.document, user);
  return user;
}

export const inMemoryUserRepository: UserRepository = { findByDocument, create };

The services that depended on UserRepository received it as a parameter:

export async function register(
  input: RegisterInput,
  users: UserRepository,
): Promise<User> {
  const existing = await users.findByDocument(input.document);
  // ...
  return users.create(input);
}

At the call site, the temporary seam was explicit:

await register(input, inMemoryUserRepository);

That parameter was deliberate scaffolding. It allowed the Use Cases to progress against the contract while making the temporary in-memory choice visible wherever the service was called.

Later, the Postgres implementation of UserRepository became available. We began removing the extra repository parameter and moving toward an agreed convention: import the repository and use it inside the service. That convention itself would become part of the question.

import { postgresUserRepository } from '../infrastructure/repository/postgres.user.repository';

export async function register(input: RegisterInput): Promise<User> {
  const existing = await postgresUserRepository.findByDocument(input.document);
  // ...
  return postgresUserRepository.create(input);
}

That was the direction of the refactor, not the conclusion of the design. It removed the temporary parameter and restored consistency with the surrounding code, but it also moved the implementation choice directly into the service and removed the visible substitution boundary. In PHP, I knew exactly where each responsibility lived. In TypeScript, the functional style I was working in didn't use those mechanisms.

In the OOP style, each responsibility had an obvious home: a small interface supported Interface Segregation; constructor injection supported Dependency Inversion; a Service Container selected implementations and assembled the graph; tests supplied another implementation of the same interface. The direct-import style looked different enough to raise the real question:

Am I giving up Interface Segregation, Dependency Inversion, centralised composition, or isolated testing? Is functional TypeScript unsuitable for these principles, or am I looking for their OOP mechanisms instead of their functional equivalents? Should this service become a class, or can the functional style preserve the same design qualities from implementation through testing?

The refactor did not reveal a missing principle. It revealed a comparison worth making: for every responsibility that had an obvious home in the OOP style, what technique (and what language structure) gave it an equivalent home in the functional style?

That comparison turned out to be a useful exercise in itself. Not just which pattern to use, but what is a principle, what is a mechanism, and what is a language structure. Where each of those pieces actually plays its role. The rest of this article works through that distinction, one responsibility at a time.

Preserve the responsibilities, change the mechanisms

The comparison becomes clearer when the creation of one service is separated from the composition of the whole application:

Design responsibility Common OOP mechanism Functional TypeScript mechanism
Keep the consumer contract narrow A small, consumer-specific interface A small structural contract
Create one service instance Invoke a class constructor directly or through a dedicated factory Invoke a service factory such as makeRegistrationService(...)
Retain injected dependencies Private object fields The returned functions' lexical closures
Compose the application graph Invoke constructors/factories manually at the composition root, or use a Service Container Invoke service factories manually at the composition root, or use a Service Container
Expose the wired application The entry point receives or resolves a root service/application object The composition function returns an application facade with already-wired operations
Test a consumer in isolation Inject a fake/mock implementation through the constructor Pass a structural or duck-typed double to the service factory

This makes the factory equivalence explicit. makeRegistrationService(users) is doing two familiar jobs at once: its parameters are the functional counterpart of constructor injection, and invoking it is the functional counterpart of constructing the service through new or through a small OOP factory. The returned closure or object of functions is the service instance.

It also keeps composition, composition root, and Service Container distinct:

  • Composition is the activity of assembling the graph.
  • The composition root is the application location where that activity happens.
  • A Service Container is one optional mechanism for performing composition and resolution, often with lifecycle, scope, or discovery features. It can be used in either an OOP or functional application.
  • An explicit composition function is manual composition, not a complete replacement for every container capability.

The composed result is another role again. The application.register operation on the returned application facade is a ready-to-use entry point into the wired graph. It is not a Service Container because callers are not resolving arbitrary services by token, and it is not managing service lifecycles. If application code asks a container for dependencies directly, that moves toward the Service Locator pattern rather than dependency injection.

None of these mechanisms creates a design principle by itself. A large interface still violates ISP. A constructor or factory typed to a concrete class still violates DIP. A container or composition function can centralise poor dependencies as efficiently as good ones. The value comes from assigning each responsibility deliberately.

Import/export syntax is not part of the comparison; both styles use ordinary module boundaries. The meaningful question is where the concrete implementation is selected. In the opening refactor, the Use Case selects postgresUserRepository itself and hard-wires the detail. In the mapped design, the composition root selects it and the service factory receives only the UserRepository contract.

The discovery wasn't any of the individual concepts, they were all familiar. It was the mapping between coding styles. How do OOP and functional TypeScript use different techniques and language structures to preserve Interface Segregation and Dependency Inversion, from implementation through isolated testing? Asking that comparative question put contracts, constructors, factories, closures, composition, containers, facades, and test doubles in their respective roles. The concepts stayed the same; the mechanisms changed.

That comparison opened a second layer: what structure in the language makes each technique possible? Class constructors and object fields create and retain dependencies in the OOP route. First-class functions and lexical closures do the equivalent work in the functional route, while ordinary function application composes the graph. TypeScript's structural type system checks contracts without nominal declarations. JavaScript's dynamic dispatch allows duck-typed doubles at runtime, while TypeScript can check the same doubles structurally before tests run. The organizing chain is therefore not only principle → technique, but design responsibility → technique → enabling language structure.

Map responsibilities, not syntax

Dependency Inversion and dependency injection are related, but they are not the same thing:

  • Dependency Inversion (the D in SOLID) is a principle about direction: high-level policy must not depend on low-level detail; both depend on abstractions.
  • Dependency injection is a technique that serves it: bind a concrete dependency outside the code that consumes it.

The OOP version stores an injected dependency in an object:

class RegistrationService {
  constructor(private readonly users: UserRepository) {}

  async register(input: RegisterInput) {
    const existing = await this.users.findByDocument(input.document);
    // ...
  }
}

The functional version stores the same dependency in a closure:

function makeRegistrationService(users: UserRepository) {
  return {
    async register(input: RegisterInput) {
      const existing = await users.findByDocument(input.document);
      // ...
    },
  };
}

Both consumers depend on UserRepository, not on a database implementation. Both receive the concrete dependency from somewhere else. The difference is where the language stores the provided value: an object field in one case, a lexical environment in the other.

Composition completes the mapping:

// composition/application.ts
import { postgresUserRepository } from '../infrastructure/repository/postgres.user.repository';

function createRegistrationApplication(users: UserRepository) {
  const registration = makeRegistrationService(users);
  return { register: registration.register };
}

const application = createRegistrationApplication(postgresUserRepository);

await application.register(input);

The composition root chooses the Postgres implementation, injects it once, and receives an application facade. Calling application.register does not choose, construct, or locate a repository. In a container-based application, a Service Container may perform this composition at the root. Here the composition function performs it manually. Neither the composition function nor the returned facade is itself a Service Container.

This is also where Interface Segregation fits. UserRepository should describe only what the registration Use Case needs. Structural typing does not guarantee ISP (nothing prevents us from declaring a fat contract), but it removes much of the implementation cost of keeping contracts small. Any value with the required shape can satisfy the consumer's contract without joining an inheritance hierarchy or declaring implements. (More details about implements down in the article.)

Service factories, closures, and composition

Three elements do different work here: the service factory creates a service, its parameters are the injection boundary, and the returned functions' closures retain the injected dependencies.

At the service level, calling makeRegistrationService(users) supplies the contract-typed dependency and creates the service. Every returned function then closes over users. This is the direct functional counterpart of a constructor receiving a value, assigning it to a private field, and producing an object instance, without exposing the dependency to every service call.

At the application level, a composition function can invoke several service factories and build the graph. The next example generalises the earlier registration-only case into a composition function for the full application graph:

interface ApplicationDependencies {
  users: UserRepository;
  mailer: Mailer;
  clock: Clock;
}

function createApplication(dependencies: ApplicationDependencies) {
  const registration = makeRegistrationService(dependencies.users);
  const profile = makeProfileService(dependencies.users);
  const reminders = makeReminderService(dependencies.mailer, dependencies.clock);

  return {
    register: registration.register,
    getProfile: profile.get,
    sendReminders: reminders.send,
  };
}

Call createApplication(...) once at the composition root, and each returned service closes over only the slice of the graph it needs; collectively, those services expose the complete, already-wired application. Production passes database, mail, and system-clock implementations. Tests pass in-memory repositories, recording mailers, and fixed clocks. The consumers remain unchanged.

Closure-based composition can make a Service Container unnecessary for a simple, static graph, but it is not a full replacement for the abstraction. The composition function builds the graph and each returned closure retains its relevant part. Together they cover the container's core composition responsibility: construct the graph centrally, bind implementations to contracts, and expose ready-to-use services. A container may additionally provide autowiring, named bindings, scopes, lifecycle management, decorators, interception, or plugin discovery, and it remains available in functional code when those capabilities earn their cost. In TypeScript, autowiring still needs runtime anchors such as classes or explicit string/symbol tokens; erased structural interfaces cannot be resolved directly. Manual composition is sufficient when those capabilities are not needed.

The two routes can now be summarised without treating module syntax as part of the comparison:

  • OOP: segregated interface → constructor/factory → dependencies retained in object fields → manual or container-assisted composition → root application object
  • Functional TypeScript: structural contract → service factory → dependencies retained in closures → manual or container-assisted composition → application facade

The architecture is preserved because each responsibility still has an explicit home. What changes is the default mechanism: lexical scope replaces instance fields, service factories replace construction through new, structural conformance replaces nominal declarations, and explicit composition can replace container resolution when the graph does not need richer container capabilities.

Anton van Straaten's fictional Qc Na koan captures the first equivalence: "objects are a poor man's closures; closures are a poor man's objects." Both bundle behaviour with retained state. Here that state includes the in-memory repository's Map and, in each service closure, precisely the dependencies that service needs.

Structural typing: the conformance mechanism

Service factories and closures answer how one service is created and retains its injected dependencies; the composition root answers where the full graph is assembled. Structural typing answers a simpler question: how does the compiler know a value satisfies the contract its consumer expects? It's what makes the functional mapping safe, not just short.

In a structurally typed system, a value satisfies a type by having the right shape: the required members, with compatible types. Names and declarations are irrelevant. UserRepository defines one such shape:

interface UserRepository {
  findByDocument(document: string): Promise<User | null>;
  create(data: NewUser): Promise<User>;
}

Any value with those two methods, and compatible signatures, has that shape. So when the in-memory repository assigns its object literal to that type. Consider:

export const inMemoryUserRepository: UserRepository = { findByDocument, create };

That single line is the conformance check. It's compile-time, exhaustive, and free: if the object is missing a method, has one with an incompatible signature, or the contract later grows, this line stops compiling. No implements, no registration, no adapter class. And it generalises: any object literal, class instance, or factory result that has the shape is a UserRepository. The contract is decoupled from every implementation's ancestry, which is why an in-memory object literal and a Postgres-backed implementation can be substituted at the composition root without changing a consumer.

You can watch the check evaporate the moment it's done its job. The in-memory repository didn't need implements. A Postgres-backed class can still use it for clarity, but it's optional, and it disappears at runtime. The TypeScript source:

class PostgresUserRepository implements UserRepository {
  async findByDocument(document: string) { /* ... */ }
  async create(data: NewUser) { /* ... */ }
}

compiles to plain JavaScript with no trace of the contract:

class PostgresUserRepository {
  async findByDocument(document) { /* ... */ }
  async create(data) { /* ... */ }
}

The interface and implements annotation disappear because they are type-system constructs. The class remains because a class is also a runtime JavaScript construct. Conformance was proven once, before the program ran, and then discarded. It's also why a TypeScript DI container can't autowire by interface the way C# or PHP can: at runtime there's no UserRepository to resolve against, only classes and string/symbol tokens. The same erasure that keeps contracts lightweight is the reason reflection-based containers cannot autowire by interface and must use runtime classes or explicit tokens.

This is also where the I of SOLID becomes cheaper to practise. A small contract requires little implementation ceremony (no base class, no implements, no registration), so keeping interfaces role-specific adds less friction. In a nominal OOP language, each new segregated interface adds a declaration that its implementations must adopt; structural typing removes that declaration tax. It does not guarantee Interface Segregation, but it makes the principle easier to apply consistently.

The contrast that makes this concrete is a nominal language, PHP, the reference OOP case here:

final class PostgresUserRepository implements UserRepository { /* ... */ }

function register(UserRepository $users): void { /* ... */ }

Here conformance is declared. An object with exactly the right methods but no implements UserRepository is not a UserRepository: pass it to register() and PHP throws a TypeError. Same shape, wrong ancestry, rejected. This is one reason adapters and containers become more prominent in nominal ecosystems: conformance is explicitly declared, so wiring becomes a first-class activity with its own tooling.

One distinction worth stating now, because it drives the rest of the post: TypeScript is structural for interfaces, object types, and (mostly) classes, and it checks that conformance statically, before the program runs. "Checked statically" is easy to wave past, but it's the entire difference between structural typing and the thing it gets mistaken for. And the fastest place to feel that difference isn't in production at all. It's the moment you sit down to write a test.

And I am a Test-Driven Developer. Therefore...

Testing: where duck typing walks back in

The style survives contact with production easily enough. The seam is typed, the closure captures a contract-typed value. Where it gets interesting is the first time you write a test.

To test a service in isolation, you need a stand-in for its dependency, a repository that never touches a database. In JS/TS we've done this for years with an ad-hoc object: just the methods the test exercises, nothing more. And here the old instinct kicks in, reach for a loose double:

// duck-typed double: no contract in sight
const users = { findByDocument: async () => null } as any;

This works. The test runs, the service calls findByDocument, the call resolves. That's duck typing: the object is accepted because, at the moment of the call, it happens to have the method. Nothing checked its shape ahead of time; the as any explicitly threw the check away.

And it raises the question this whole post circles: is that the same thing as structural typing? It feels identical, both say "shape is enough, ancestry is irrelevant." But the difference is exactly the when. Type the same double against the contract instead:

// structurally-typed double: checked against the contract, now
const users: UserRepository = {
  findByDocument: async () => null,
  create: async (data) => ({ id: 'x', ...data, createdAt: new Date() }),
};

Now the compiler enforces the whole shape before the test runs. Forget create, or let the real UserRepository grow a method, and this double stops compiling; the test tells you it drifted. The as any version compiles happily and only fails later, at runtime, if that path is even exercised.

Same philosophy, opposite failure mode. The loose double (as any) is widely used and genuinely convenient, and it's quietly the reason so many of us assume duck typing and structural typing are one thing. They aren't: typing the double : UserRepository is the small discipline that keeps a test double in the structural camp, and it's worth doing. But the recommendation isn't the point here. The point is that the moment you write a mock is the moment the two concepts visibly separate, which is exactly what the next section pulls apart.

Untangling the five concepts

Five ideas have been doing distinct work so far. Placing them side by side makes the boundaries explicit:

Concept What it is What it is not
Dependency inversion / injection DIP: a principle about direction; depend on abstractions (the D in SOLID). DI: a technique serving it; bind concretions elsewhere A framework, a container, or anything inherently class-shaped
OOP constructs Classes, constructors, implements; one mechanism for DI and encapsulation The definition of DI, or a requirement for Interface Segregation or Dependency Inversion
Closures Functions capturing their environment; another mechanism for retained private state, injected dependencies, and explicit graph composition A Service Container abstraction by definition, or a hack until "real" OOP arrives
Structural typing Static conformance decided by shape; checked before the program runs A dynamic-language feature; permission to skip contracts
Duck typing Runtime conformance: "if it quacks"; discovered at the call site, or not at all A synonym for structural typing

Read down the "what it is not" column and the responsibilities separate cleanly. Dependency injection is not a framework: an explicit composition function can bind the graph as truly as a container. OOP constructs are not the definition of DI: they're one mechanism among several, the one that happens to dominate nominal ecosystems. Closures are not a hack or a container by definition: they are a language mechanism that can retain one dependency or the complete composed graph.

The two that cause the most trouble are the last ones: structural typing vs duck typing. They share a philosophy, behaviour over ancestry, shape over name, and in TypeScript they even look identical to write, which is why they get treated as one thing. They are not. The difference is when the shape is checked. Structural typing checks it at compile time, by a type checker, before the program runs; the failure is a red squiggle in your editor. Duck typing checks it at runtime, at the moment of the call, by the call itself; the failure is a thrown error, or worse, silence, if the missing method simply never gets reached on that path.

Which answers the question the testing section left open: if structural typing isn't what makes duck typing possible, what does? The enabler is dynamic dispatch, the language resolving x.quack() against whatever x actually is at call time, with no prior type commitment required. That's a property of the runtime, not of the type system, and it's independent of whether conformance is judged by shape or by declaration. The clean proof is Python: it has had duck typing forever, with no structural type system at all; typing.Protocol (PEP 544) later added static structural checking as an opt-in for external type checkers, and the duck-typed runtime underneath didn't change one bit. So duck typing and structural typing aren't two names for one idea, they're independent answers to two different questions, how? and when?, and a language can choose each answer separately.

The language field guide

Put the two questions on two axes, how conformance is decided (by shape, or by declaration) and when it's checked (statically at compile time, or at runtime), and every language lands in a cell:

Checked statically (compile time) Checked at runtime
By shape TypeScript, Go (structural typing) Python, JS, Ruby (duck typing)
By declaration C#, Java (nominal + static) PHP with type hints (nominal + runtime)

The cells people forget are the interesting ones.

  • TypeScript: shape, static, and loose. An ad-hoc object literal conforms on the spot, no named type required. The cheapest contracts of any mainstream language. TypeScript provides static structural checking over a dynamically typed JavaScript runtime, so once the types are erased, what's left is duck typing.
  • Go: shape, static, and not loose. Interfaces are satisfied implicitly (structural, a type never says implements), but conformance still needs methods declared on a named type; there are no ad-hoc conforming literals and no runtime "try the call and see." Interface satisfaction operates through named interface types rather than TypeScript-style ad-hoc object compatibility. This is the answer to "is there structural typing without any duck typing?". Go is it, and it isn't a compromise. The idiomatic Go move of defining tiny consumer-side interfaces is Interface Segregation and structural typing working together, straight out of the textbook.
  • Python / JS / Ruby: shape, runtime. Classic duck typing, enabled by dynamic dispatch. Python then bolts on optional static structural typing via typing.Protocol (PEP 544) for anyone running a type checker, without touching the duck-typed runtime, the cleanest demonstration that the two are separable.
  • PHP: declaration, runtime. Nominal, but enforced at call time. With type declarations, objects of classes that declare implements pass; a mismatch is a TypeError when the call happens, not a compile error (PHPStan/Psalm drag the check earlier, as a lint). Drop the declarations and PHP becomes dynamically typed: no type enforcement on parameters, method calls resolved at runtime, but objects are still class instances, not ad-hoc shapes. That double identity, nominal-when-typed, dynamic-when-not, plus autowiring by type declaration is the same story that made the containers from section 3 inevitable.
  • C# / Java: declaration, static. Nominal, checked at compile time. The full ceremony (declare the interface, implements it, register it, inject it) and perfectly capable of clean dependency-inverted designs; the container exists to amortise the wiring cost the nominal type system creates in the first place.

The grid shows these are independent axes, and real languages occupy all four cells. Go is structural and statically checked, but without TypeScript's ad-hoc object compatibility; TypeScript is structural-and-loose yet fully static; Python is duck-typed with an optional structural upgrade; PHP is nominal without being static, the quadrant people forget exists. "Structural" and "duck" are not synonyms, and "nominal" and "static" are not the same axis. Once the grid is visible, the testing question becomes precise: a TypeScript double can rely on JavaScript's runtime duck typing, or it can be checked structurally before the test runs. The object may look the same; the guarantee is different.

A good way to use them

None of this argues against classes, and none of it argues against containers. It argues for choosing the mechanism on purpose. A few defaults fall out of everything above:

  • Keep contracts in the domain, named in the domain's language. UserRepository belongs in domain/user.ts, not in the infrastructure that implements it; the consumer owns the interface, the implementation conforms to it. This is the Go consumer-defined-interface instinct and Interface Segregation in one move.
  • For simple functional services, a factory + closure is a natural default. The dependency is captured once and stays private. Keep parameter passing for genuinely local composition or deliberate scaffolding. Put the complete graph in an explicit composition root (createApplication or equivalent), invoke it once with production implementations, and retain the returned application facade as the wired root object. That is where implementation choices remain centralised and tests gain a single, typed substitution boundary.
  • Treat class-vs-closure as a mechanism choice, not a moral one. Pick by team convention and by whether you genuinely need identity or lifecycle semantics, not because one of them is "real" dependency injection. They both are.

It's worth naming the design principle underneath, because it's the reason the cheap option is also the good one. In Vlad Khononov's Balanced Coupling model, a shared contract is the weakest, most distance-tolerant form of coupling between two components, exactly what you want across a module boundary, where the two sides may change and ship independently. Structural typing makes that weakest level of coupling nearly free to express, so in TypeScript the best-balanced design and the least-ceremony design are the same design. The one discipline the model insists on: keep the wiring explicit and greppable, a named seam you can find, because Balanced Coupling's warning is against implicit coupling, and implicit coupling is also structural typing's failure mode. Which is the honest counterpoint.

The honest counterpoint

The price of making conformance free is that conformance becomes implicit. Anything with the right shape satisfies a contract, including things that match only by accident. A single-method contract like { execute(): void } is satisfied by half the objects in a codebase; the type checker will happily accept a wrong one that merely fits. The narrower and more generic the contract, the more coincidental matches it invites, so the defence is to keep contracts role-named and non-trivial (UserRepository, not Doer), so that matching the shape actually means matching the intent.

Implicitness costs tooling, too. Without implements, "find all implementations of this interface" is a weaker query than in a nominal language, and renaming a contract member doesn't announce, at the declaration site, everyone who just broke. You lean harder on the compiler and on find-references, and a little less on the class hierarchy telling you who's involved.

The mitigation turns out to be the same thing as the recommendation from the previous section: an explicit, greppable composition root. A deliberate conformance point, const impl: Contract = ..., typed against the contract, living in that known location, turns implicit shape-matching back into a visible, findable decision. It's also, not coincidentally, the same discipline that keeps a test double structural rather than duck-typed. The functional style doesn't remove the need to be deliberate about coupling; it relocates the deliberateness from the type declaration to the wiring, and rewards you for keeping that wiring in the open.

Checklist

A quick test for "am I doing DI properly in this style?", whether or not you reached for a class:

  • Does the consumer depend on a contract, not a concrete implementation? (Take the contract as a factory parameter and capture it.)
  • Is the binding external to the consumer, captured by a service factory and selected at the composition root, rather than constructed inline?
  • Is every implementation, including test doubles, typed against the contract (: UserRepository), so drift fails at compile time instead of at runtime?
  • Are contracts small and role-named, so structural matching signals intent rather than coincidence?
  • Is the complete dependency graph explicit and greppable in one composition root, rather than having consumers select concrete implementations throughout the application?
  • Did you pick class-vs-closure for a real reason (convention, lifecycle, identity), not out of habit or a belief that one is "real" DI?

Recap

The article started with a refactor that removed a temporary parameter and raised a question: was I giving up Interface Segregation and Dependency Inversion by moving from OOP to functional TypeScript, or was I looking for OOP mechanisms where functional equivalents existed?

The answer turned out to be a comparison worth making. For every responsibility that had an obvious home in OOP, there was a functional technique that gave it an equivalent home:

  • Interface Segregation lives in small, role-named contracts. Structural typing removes the declaration tax that keeps contracts fat in nominal ecosystems.
  • Dependency Inversion lives in depending on abstractions, not on concretions. A factory parameter captures a contract-typed dependency as cleanly as a constructor.
  • Dependency Injection lives in binding concretions outside the consumer. A service factory and closure retain injected state as truly as an object field.
  • Composition lives in a single root where implementations are selected and the graph is assembled. A composition function does this as truly as a Service Container.
  • Conformance lives in shape, not ancestry. Structural typing checks it statically, before the program runs. Duck typing discovers it at runtime, at the call site. Same philosophy, different when.
  • The language field guide put that distinction on two independent axes:
    • How conformance is decided: by shape or by declaration.
    • When it's checked: statically at compile time, or at runtime.
  • Real languages occupy all four cells:
    • Go is structural and statically checked, but without ad-hoc object compatibility.
    • TypeScript is structural and loose, yet fully static.
    • Python is duck-typed with an optional structural upgrade.
    • PHP is nominal without being static.
  • "Structural" and "duck" are not synonyms, and "nominal" and "static" are not the same axis.
  • The honest counterpoint: making conformance free makes it implicit. Anything with the right shape satisfies a contract, including things that match only by accident. The defence is role-named, non-trivial contracts and an explicit, greppable composition root. A deliberate conformance point, typed against the contract, turns implicit shape-matching back into a visible, findable decision.
  • The principles stayed the same. The mechanisms changed:
    • Classes, constructors, and implements are one set of mechanisms.
    • Closures, factories, and structural contracts are another.
  • Neither set is the definition of the principles they carry. Picking between them is a mechanism choice, not a moral one.
  • The one discipline that travels across both styles: keep the wiring explicit and greppable. A named seam you can find is the difference between deliberate coupling and accidental coupling, whether the seam is a constructor parameter or a factory argument.

Glossary

  • OOP — Object-Oriented Programming: a programming style that organises state and behaviour around objects. For comparison, this article uses a common class-based arrangement: interfaces, constructors, implementations, and a Service Container.
  • SOLID: a family of five design principles associated with maintainable and adaptable software. This article focuses only on its I and D.
  • ISP — Interface Segregation Principle: consumers should not be forced to depend on operations they do not use; prefer small, role-specific contracts.
  • DIP — Dependency Inversion Principle: high-level policy should not depend directly on low-level details; both should depend on abstractions, and details should depend on those abstractions.
  • DI — Dependency Injection: a technique for supplying dependencies from outside the consumer. DI can support DIP, but the two are not synonyms.
  • Closure: a function together with the lexical environment it retains, allowing injected values to remain available after the factory that received them has returned.
  • Service Container: a central assembler or registry that selects implementations and wires services, often with additional lifecycle or resolution features.
  • Composition root: the single application location where concrete implementations are selected and the dependency graph is assembled.
  • Seam: a place in code where behaviour can be varied without editing the code that uses it. Coined by Michael Feathers in Working Effectively with Legacy Code. In this article, the repository parameter is a seam: you swap implementations at the call site without touching the service.

Further reading and references

Glossary concepts

Language and design mechanics

Categorias
Programming Segurança

Permissions and Authorisation: Implementing with Cedar

Disclaimer: This is the point-in-time version of my "Playbook - Permissions and Authorisation: Cedar Implementation", which I will keep up-to-date. This article is the sequel to "Permissions and Authorisation: A Practical Playbook", which covers the domain model, enforcement boundaries, and mechanism selection. Read that first. This article assumes the model is built and a policy engine is warranted.

The previous article ended with a guidance: introduce a policy engine when the model combines roles with ownership, relationships, tenant containment, and attributes; when the same decision must be made in several services; or when policy review, simulation, traceability, or controlled change is a real requirement. Cedar is one concrete option when that point is reached. This article walks through how to apply the playbook's model using Cedar specifically and where Cedar stops being the answer.

What Cedar is

Cedar is a policy language and decision engine developed by AWS and released open-source under Apache 2.0. It evaluates an authorisation request with four parts, being principal, action, resource, context (called PARC), plus a set of entities representing trusted domain facts and their relationships. It returns Allow or Deny and decision diagnostics.

Cedar's evaluation semantics provide three useful safety properties:

  1. Default deny. No matching permit means Deny. There is no implicit allow.
  2. Forbid wins. A matching forbid overrides any matching permit. Guardrails are expressible as first-class policy, not afterthoughts.
  3. Errors skip the affected policy. A policy evaluation error causes that policy to be skipped and reported in diagnostics rather than automatically determining the entire decision. The request continues to be evaluated against remaining policies.

The third rule makes validation and diagnostics operationally important. A faulty policy does not itself cause a global outage, but it can be skipped while another permit still allows a request that the faulty policy was meant to restrict. Validate policies against the schema before publication, alert on evaluation diagnostics, and test both policy and schema changes.

A Cedar design normally contains:

  • a schema for entity types, attributes, memberships, actions, and context shapes;
  • entities representing trusted domain facts and relationships;
  • permit and forbid policies;
  • a policy store and change process;
  • an application adapter that constructs the PARC request and relevant entity slice, invokes Cedar, records the decision, and enforces it.

What Cedar does not solve

Cedar is a decision engine, not a complete authorisation system. This is pivotal to understand what is not Cedar's responsibility. It does not:

  • authenticate users or issue/validate JWTs;
  • decide which entity data is true: your application must assemble trusted, correctly scoped entity data;
  • filter a database query automatically or protect a storage bucket on its own;
  • replace validation of input, tenancy checks, audit retention, rate limits, or business invariants;
  • provide a complete UI, approval workflow, or governance process for users editing policies.

If policy authors are customers or non-engineering staff, design policy administration as a product: constrained templates, preview/simulation, approval and rollback, audit history, and strict meta-permissions for who may grant which access.

When Cedar is a good fit

Cedar is particularly strong when a system needs combinations of RBAC, ownership/relationship rules, tenant containment, and attributes; when decisions are shared across services; or when policy review and explainability matter.

Use groups to represent broad roles and policies to grant role capabilities. Add resource relationships or attributes for rules that roles cannot express cleanly. Keep individual grants and exceptions narrow, scoped to both principal and resource where possible. Prefer fine-grained permissions in the model, then aggregate them into user-facing product roles or screens.

Cedar is not the only policy engine, and it is not always the right one. If your rules are few, stable, and local to one service, centrally tested application code is simpler and clearer. If you need a full relationship-based access control system with deep graph traversal, consider whether Cedar's entity model is expressive enough for your relationship depth or whether a dedicated ReBAC system is more appropriate. Choose based on the behaviour the system needs, not the novelty of the tool.

Implementing Cedar: a step-by-step approach

1. Start with one high-value boundary

Choose one coherent domain, such as organisation membership, documents, or projects, not the entire legacy permission surface. Keep existing authorisation in place elsewhere. Define the success measure: for example, all document operations are evaluated at one server-side boundary and the decision can be explained from logs.

This mirrors the playbook's general guidance: centralise decisions early enough that the model can evolve deliberately, rather than attempting a big-bang migration of every permission surface at once.

2. Define the Cedar schema and action vocabulary first

Define the namespace, entity types, action groups, and action applicability before drafting many policies. Ensure each action identifies the permitted principal and resource types and the specific transient context shape it accepts.

namespace ExampleApp {
  entity User in [Role, Organisation] {};
  entity Role {};
  entity Organisation {};
  entity Document in [Organisation] = { owner: User, locked: Bool };

  action "document.read" appliesTo {
    principal: [User],
    resource: [Document],
    context: {}
  };

  action "document.update" appliesTo {
    principal: [User],
    resource: [Document],
    context: {}
  };
}

This is illustrative only. The schema must reflect the actual domain and its authoritative data sources. The Cedar schema defines what an authorisation request and its entities are allowed to look like; it does not establish where those facts come from or whether they are trustworthy. That is the responsibility of the adapter and the data contract described in step 5. The action vocabulary is where the playbook's guidance on business actions applies directly: use document.read, document.update, invoice.approve — not HTTP verbs or UI labels. Make the resource explicit even for create and list operations, where the resource is normally the destination container or tenant.

3. Model policy rules as business rules

Policies should be specific and readable. A role grant and an owner rule may coexist; a forbid can express a guardrail that must win even if a role policy permits access.

// Role-based: document readers can read any document in their scope.
// Assumes the user's role membership is represented in the entity graph.
permit (
  principal in ExampleApp::Role::"document_reader",
  action == ExampleApp::Action::"document.read",
  resource
);

// Ownership-based: owners can update their own unlocked documents
permit (
  principal,
  action == ExampleApp::Action::"document.update",
  resource
)
when { resource.owner == principal && !resource.locked };

// Guardrail: locked documents cannot be updated, even by the owner
forbid (
  principal,
  action == ExampleApp::Action::"document.update",
  resource
)
when { resource.locked };

Do not paste this example into production unchanged. In particular, scope policies as tightly as the domain requires and validate all policy text against the deployed schema.

The forbid-wins semantics are what make Cedar's guardrails trustworthy. A locked-document rule expressed as forbid will override any permit including future permits you haven't written yet. This is qualitatively different from expressing the same constraint as a negative condition inside every permit, which silently stops applying when a new permit forgets to include it.

4. Create one authorisation adapter

Application code should call a small, well-tested boundary with a request such as:

authorize({ principal, action, resource, context }) → allow/deny + decision metadata

The adapter:

  • resolves canonical IDs (opaque, immutable — not display names or email addresses);
  • loads the minimum authoritative entity slice (principal, resource, and the relationships the policies might traverse);
  • calls the Cedar authorizer;
  • handles diagnostics according to the service's safety requirements;
  • emits safe audit telemetry (request/correlation ID, principal/resource type and opaque IDs, action, decision, applicable rule identifiers and version, evaluation errors, latency);
  • blocks execution on denial.

The adapter should not accept arbitrary Cedar entities or policy text from an untrusted caller. Entity data comes from trusted application sources; policy text comes from a versioned, reviewed policy store. Never from the request.

This is the same enforcement boundary the playbook describes, now with a concrete implementation: the adapter is where route additions cannot silently bypass the decision, because every protected operation passes through it.

5. Assemble the entity slice carefully

Cedar evaluates policies against the entities you provide, not against your database. The adapter must load the minimum authoritative entity slice: the principal, the resource, and the relationships the policies might traverse (group memberships, tenant containment, ownership links).

This is where the playbook's data contract guidance becomes concrete. For each entity attribute and relationship:

  • What is the canonical source?
  • What is the freshness expectation?
  • Who owns the data?

Keep principal, action, and resource facts in their respective models. Use request context only for transient, action-specific facts such as an MFA assertion, request time, or an IP/network signal not as a duplicate source for identity, role, tenant, or resource ownership. If the entity slice is wrong, the decision is wrong, regardless of how correct the policies are.

For “may Alice read Document X?”, the adapter might supply:

Fact Cedar input Authoritative source
Who is making the request? User::"alice", including role and tenant Identity and membership service
What is being accessed? Document::"x", including owner, classification, and locked state Document service/database
How are they related? Alice's group memberships; the document's folder and tenant Membership and document data
What is true only for this request? Verified MFA assertion, request time, client network Validated session/token and request infrastructure

The policies determine which of those facts are needed. A rule that permits Group::"editors" needs Alice's group membership; a rule that permits only the document owner needs its current owner; a forbid for locked documents needs the current locked state. The adapter assembles and validates this input; the client does not.

Why "carefully": three failure modes, all silent.

  1. Missing relationships. A policy says principal in Group::"editors". If you don't load Alice's group memberships, Cedar can't match the policy. It evaluates as if Alice is in no groups. The decision is Deny even though Alice is an editor. The policy is correct; the data slice is wrong.
  2. Stale data. Alice was removed from the editors group 5 minutes ago, but your entity slice was cached from 10 minutes ago. Cedar allows a request that should be denied. The freshness question above is about this.
  3. Wrong source. You put Alice's role in the request context (which the caller controls) instead of loading it from your identity store. A malicious or buggy caller passes role: admin in the context and Cedar grants admin access. The guidance above is warning against exactly this: context is for transient facts (MFA, IP, time), not for identity, role, or ownership, because those must come from trusted sources.

The "minimum" part: you don't load your entire user database into every authorisation call. You load the slice that the policies might traverse for this request. Too little → wrong decisions. Too much → latency and unnecessary data exposure. The "carefully" is about getting that boundary right.

6. Handle diagnostics as a first-class concern

Because evaluation errors are skipped rather than fatal, diagnostics are not optional telemetry, but safety signal. A policy that errors is a policy that is not applying. If that policy was a forbid guardrail, the request may be allowed by a different permit that the forbid was meant to override.

Handle diagnostics according to the service's safety requirements:

  • Alert on evaluation errors at a rate that indicates a policy or entity-slice problem, not a transient blip.
  • Treat a diagnostics-only decision (no matching permit or forbid, but errors present) as Deny unless the service has a deliberate, documented reason to do otherwise.
  • Include diagnostic information in audit records so post-incident investigation can reconstruct why a decision was made.

Cedar-specific verification

In addition to the general test strategy from the playbook, Cedar introduces its own verification surface:

Layer Verify
Schema validation Schema compiles, entity types and actions are consistent, context shapes match action definitions
Policy unit tests Each permit and forbid produces the expected decision for representative entity slices
Entity-slice mapping tests The adapter loads the correct entities and relationships for a given request. No missing relationships, no stale data
Diagnostics-handling tests Evaluation errors are surfaced, alerted, and do not silently allow access
Schema-change tests Adding, removing, or changing entity attributes or actions does not silently alter existing decisions

For every new policy, include at least one must allow, must deny, and must not leak scenario. Test actions, not UI controls, because direct API calls and background execution bypass the UI. This is the same discipline as the general playbook, now applied to Cedar's permit/forbid semantics.

Operational checklist for Cedar

Before implementation

  • One high-value boundary chosen, with existing authorisation preserved elsewhere.
  • Cedar schema reflects the actual domain: entity types, attributes, memberships, actions, and context shapes.
  • Action vocabulary uses business actions, not HTTP verbs.
  • Entity data sources identified: canonical source, freshness, and ownership for each attribute and relationship.
  • Adapter design defined: ID resolution, entity-slice loading, Cedar invocation, diagnostics handling, audit telemetry, and enforcement.

Before rollout

  • Policies validate against the schema in CI.
  • Policy changes have review, audit, and rollback paths.
  • The adapter is the sole entry point for Cedar evaluation — no bypass paths.
  • Entity-slice loading is tested for correctness and minimal scope.
  • Diagnostics are alerted on, not just logged.
  • Existing data/query/storage controls still enforce tenant and ownership boundaries.
  • Negative and regression tests prove denial causes neither disclosure nor side effect.

After rollout

  • Inspect allow/deny rates, diagnostics, latency, and unexpected denials.
  • Confirm no route or job bypasses the adapter.
  • Review forbid guardrails, stale entity data, and policy-store changes on a defined cadence.
  • Record incidents and confusing access requests as new regression cases or schema improvements.

Cedar-specific anti-patterns

In addition to the general anti-patterns from the playbook:

  • Trusting unvalidated entity data: passing request-supplied attributes or relationships into Cedar without resolving them from a trusted source. Cedar evaluates what you give it — incorrect entity data can produce incorrect authorisation decisions.
  • Forgetting forbid when adding new permits: a new permit that broadens access may override a constraint that was previously enforced by the absence of a permit, not by an explicit forbid. Express guardrails as forbid so they survive new permits.
  • Ignoring diagnostics: treating evaluation errors as harmless noise. A skipped forbid is a silent security gap.
  • Overloading context with entity facts: using the context map to pass principal roles, tenant membership, or resource ownership instead of modelling them as entities and relationships. Context is for transient, action-specific facts.
  • Policy-store drift: changing policies without schema validation, version pinning, or regression tests. A policy that validated against the previous schema may error against the new one.
  • Entity-slice gaps: loading the principal and resource but forgetting the relationships the policies traverse (group memberships, tenant containment). A policy that depends on principal in Role::"admin" will deny if the Role entity is not in the slice — silently and without a clear error.

References

Categorias
Programming Technology

Permissions and Authorisation: A Practical Playbook

Disclaimer: This is the point-in-time version of my "Playbook - Permission and Authorisation", which I will keep up-to-date.

Authorisation is a domain capability, not a collection of scattered endpoint conditionals. For every protected operation, decide consistently whether a verified principal may perform a business action on a specific resource in a defined context—and enforce that decision server-side before data or side effects are exposed.

Choose the simplest mechanism that preserves one consistent, server-side decision model. A few stable rules may be clearer as centrally tested application code; a policy engine becomes valuable when rules are expressive, auditable, shared across services, or need to evolve independently of individual endpoints.

To definitions:

Permission is a grant or entitlement.

Authorisation is the request-time decision and server-side enforcement that applies those grants to a principal, action, resource, and context.

When this matters

This becomes important when a system has any of the following:

  • users with more than one role or organisation;
  • tenant, ownership, project, folder, account, or team boundaries;
  • permissions that depend on resource state, relationships, time, location, MFA, or other trusted context;
  • customer-configurable or delegated access;
  • several services or endpoints that must make the same access decision;
  • audit, compliance, support, or incident needs that require explaining why access was allowed or denied.

A small internal tool with a stable administrator/member distinction may need only a simple, centrally tested server-side check. Do not introduce a policy engine merely to avoid a short, clear rule.

The mental model

Keep authentication and authorisation distinct

  • Authentication: who is making this request? Verify identity and session/token integrity.
  • Authorisation: may that verified identity perform this action on this resource now?
  • Entitlements / relationships: which roles, tenants, ownership relations, subscriptions, and delegations are true?
  • Enforcement: where is the decision applied before sensitive data or side effects occur?

An authenticated user is not automatically authorised. Client-side checks improve the user experience but never replace server-side authorisation. A role label alone is not a complete permission model.

Separate permissions from business rules

Permission answers whether a principal may perform an action on a resource:

Can Alice approve invoice #123?

Business rules answer whether that action is valid in the resource's current state:

Can an approved invoice still be edited?

These are different questions. An authorised user can still fail business validation, and a valid workflow transition can still be forbidden for that user. Workflow state may be a deliberate authorisation input, but permissions must not become a substitute for state-transition validation or domain invariants.

Ask the same question everywhere

Express every authorisation decision as:

Can principal P perform action A on resource R in context C?

Use business actions such as invoice.approve, project.member.invite, or document.download, rather than HTTP verbs or UI labels. Make the resource explicit even for create and list operations, where the resource is normally the destination container or tenant.

Design for default deny and least privilege

Start with no access. Add narrow, reviewable grants only where a business rule justifies them. Keep explicit prohibitions for non-negotiable guardrails, such as suspended accounts, cross-tenant access, or actions requiring MFA.

Every server-side path that reads protected data, changes state, invokes a privileged integration, or produces a sensitive export needs an enforcement point. Database row-level security, query predicates, and storage access controls remain necessary defence-in-depth; an application authorisation decision does not replace them.

Build the model before choosing the mechanism

1. Map protected capabilities

Create an authorisation matrix from the domain, not from framework routes.

Principal Action Resource / container Conditions Expected outcome
Staff member case.view a case in their organisation active employment Allow
Case owner case.update their own open case not locked Allow
Organisation admin user.invite their organisation MFA completed Allow
Any user billing.export organisation billing data no finance role Deny

Include the negative cases deliberately: cross-tenant access, inactive users, deleted/locked resources, delegated access expiry, and privileged actions without step-up authentication.

2. Model the stable domain nouns and relationships

Identify principals, resources, containers, roles/groups, and the relationships that determine access. Use opaque, immutable IDs in policy-facing data; display names, email addresses, and mutable slugs are poor policy identifiers.

For a multi-tenant system, model the tenant/organisation as a first-class container. A resource should have a clear containment path, and a principal’s tenant membership should be supplied from a trusted source. Do not rely on a tenant ID supplied by the browser without resolving and validating it server-side.

3. Identify the enforcement boundaries

Document where checks occur for:

  • single-resource reads, updates, deletes, and downloads;
  • resource creation and listing, against the target container;
  • batch operations, per resource or via a deliberately designed compound decision;
  • asynchronous jobs, webhooks, internal APIs, and service accounts;
  • data stores, object storage, search indexes, and reporting/export paths.

A middleware can be a useful adapter, but it is not the model. The authorisation decision must be close enough to the domain operation that route additions cannot silently bypass it.

4. Define the data contract

Authorisation is only as trustworthy as its inputs. Define the canonical source, freshness expectation, and ownership for each principal attribute, resource attribute, and relationship. Normalise application data into a single request model before evaluating a rule.

Keep principal, action, and resource facts in their respective models. Use request context only for transient, action-specific facts such as an MFA assertion, request time, or an IP/network signal—not as a duplicate source for identity, role, tenant, or resource ownership.

Permission implementation practices

Address listings, creates, and batches deliberately

  • Create: authorise against the verified destination container before creating the resource.
  • List: authorise the container-level list action and apply equivalent tenant/visibility constraints in the query. A list decision alone does not make every item safe to reveal.
  • Batch: evaluate each target resource or use a deliberately designed compound authorisation rule; do not authorise only the first item.
  • Move/share: evaluate all affected source and destination relationships.

Make rule changes a controlled deployment

Version authorisation rules, their supporting model and mapping code, and regression tests together. Validate rules and their configuration in CI. For dynamically managed rules, use staged rollout, approval, rollback, and versioned audit records. Treat model-contract changes as compatibility changes: a change to attributes, relationships, or resource types can alter existing decisions unexpectedly.

Observe decisions without leaking data

Record enough to investigate: request/correlation ID, principal/resource type and opaque IDs where appropriate, action, decision, applicable rule identifiers and version where available, evaluation errors, and latency. Protect logs and avoid raw tokens, sensitive attributes, or full rule payloads unless access and retention are explicitly controlled.

Test strategy

Test authorisation as executable security behaviour, not merely syntax or configuration.

Layer Verify
Decision-model tests intended grants, explicit prohibitions, default deny, and boundary values
Authorisation-boundary tests correct request-to-action mapping, canonical resource resolution, trusted data loading, and error handling
Endpoint/service tests denied calls produce no protected data or side effect; allowed calls reach only valid scope
Data-access tests queries, storage access, and exports retain tenant and visibility constraints
Regression tests known historical incidents and cross-tenant attack cases stay denied
Change tests rule/model migrations preserve decisions intentionally and make changed decisions explicit

For every new permission capability, include at least one must allow, must deny, and must not leak scenario. Test actions—not UI controls—because direct API calls and background execution bypass the UI.

Choose the authorisation mechanism

Use centrally tested application code when the rules are few, stable, local to one service, and readily understood from the domain model. Keep the decision behind a small authorisation boundary rather than copying checks across routes or handlers.

Introduce a policy engine when the model combines roles with ownership, relationships, tenant containment, and attributes; when the same decision must be made in several services; or when policy review, simulation, traceability, or controlled change is a real requirement. A policy engine does not remove the need for trusted data, enforcement at every boundary, query scoping, or governance of who may change access.

Choose based on the behaviour the system needs, not the novelty of the tool.

A common evolution path

Most systems do not need their final permission model on day one. A common progression is:

Simple role checks
        ↓
Central authorisation module or service
        ↓
Resource ownership
        ↓
Tenant isolation
        ↓
Attribute conditions
        ↓
Delegation
        ↓
Shared policies
        ↓
Policy engine, if the demonstrated complexity justifies it

This is not a universal sequence or a maturity scorecard. A product may need tenant isolation before ownership, or never need delegation at all. Treat it as a set of capabilities: adopt the next one only when a concrete product, security, or operational need makes the current model insufficient.

Starting simple is normal. The important discipline is to centralise decisions early enough that the model can evolve deliberately, rather than accumulating inconsistent route-by-route checks.

Operational checklist

Before implementation

  • Define the decision to centralise and the protected business outcome.
  • Inventory all entry points and data/side-effect paths for that domain.
  • Name domain actions, resources, containers, and trusted attributes.
  • Write allow and deny scenarios, including cross-tenant and stale/disabled-user cases.
  • Identify source, freshness, and owner of each authorisation fact.
  • Choose simple central checks or a policy engine based on demonstrated complexity.

Before rollout

  • Authorisation rules and configuration validate in CI.
  • Rule changes have review, audit, and rollback paths.
  • Every protected operation uses the authorisation boundary or an equivalent verified enforcement path.
  • List, batch, create, move, export, background-job, and service-account paths are covered.
  • Decision telemetry captures implementation version and evaluation errors safely.
  • Existing data/query/storage controls still enforce tenant and ownership boundaries.
  • Negative and regression tests prove denial causes neither disclosure nor side effect.

After rollout

  • Inspect allow/deny rates, diagnostics, latency, and unexpected denials.
  • Confirm no route or job bypasses the enforcement boundary.
  • Review exception policies, stale roles, delegations, and privileged access on a defined cadence.
  • Record incidents and confusing access requests as new regression cases or model improvements.

Anti-patterns

  • UI-only permission checks: hiding a button while leaving the API callable.
  • Route-by-route conditionals: duplicating unreviewed logic until equivalent rules disagree.
  • Role explosion: adding a new role for every exception instead of modelling the relationship or rule condition.
  • Tenant IDs from the client: trusting an unverified selector or URL parameter as access proof.
  • Unscoped list authorisation: permitting list but returning objects the caller may not read.
  • Authorisation as a magic boundary: assuming one decision protects data paths it does not govern.
  • Rule/model drift: changing domain relationships or configuration without revalidating affected authorisation decisions.
  • Ignoring decision errors: treating failed or incomplete evaluations as harmless without monitoring their impact.
  • Mutable identifiers in rules: binding access to email addresses, names, or human-facing slugs.
  • No explanation trail: being unable to answer who granted access, why it applied, and when it changed.

References

Categorias
Programming

Building Evolutionary Architectures – Chapter 2: Fitness Functions

Chapter 2 introduces the concept of architectural fitness functions, the mechanism that makes "evolutionary" more than a buzzword.

The origin: borrowing from evolutionary computing

The term comes from genetic algorithm design. In evolutionary computing, a fitness function defines what "better" means so that solutions can gradually emerge through small changes across generations. The classic example: when using a genetic algorithm to optimise wing design, the fitness function assesses wind resistance, weight, air flow, and other desirable characteristics. At each generation, the engineer asks: is this closer to or further away from the goal?

Ford, Parsons and Kua borrow this concept for software:

An architectural fitness function provides an objective integrity assessment of some architectural characteristic(s).

In software, fitness functions check that developers preserve important architectural characteristics; the "-ilities" architects care about: scalability, security, performance, maintainability, resilience.

The core idea

An evolutionary architecture supports guided, incremental change across multiple dimensions. The key word is guided. Without guidance, incremental change is just drift. Fitness functions are what provide the guidance.

The fitness function protects the various architectural characteristics required for the system. These requirements differ greatly across systems and organisations: some require intense security; others require significant throughput or low latency; others need resilience to failure. A crucial early architecture decision is to define which dimensions matter most for a given system, based on business drivers, technical capabilities, and scale.

Why this matters

Most teams have implicit architectural goals: "the system should be fast", "services should be loosely coupled", "we should be secure". The problem is that implicit goals erode. Nobody notices the slow degradation until a characteristic has already failed.

Fitness functions make the implicit explicit. They turn architectural aspirations into verifiable checks. Automated where possible, manual where necessary.

A key insight: improving one architectural dimension can accidentally harm another. Improving performance with caching might harm data freshness or security. Fitness functions act as guardrails that detect these tradeoff violations before they reach production.

Categorising fitness functions

The book defines several dimensions for classifying fitness functions:

Atomic vs Holistic

  • Atomic — tests one particular aspect of the architecture in isolation. Example: a unit test checking for cyclic dependencies in a package, or a code metric that checks cyclomatic complexity.
  • Holistic — tests a combination of architectural aspects, assessing interactions between different concerns. Example: testing the number of concurrent users within a certain latency range while caching is enabled — this simultaneously checks scalability and data freshness. Holistic functions are harder to build but capture what atomic ones miss.

Triggered vs Continuous vs Temporal

  • Triggered — executed in response to a specific event: a developer running a unit test, a CI pipeline stage, a QA person performing exploratory testing.
  • Continuous — constant verification of architectural aspects. Monitoring and alerting are the classic examples. Netflix's Chaos Monkey — which runs in production and randomly terminates instances — is a continuous holistic fitness function that forces teams to build resilient services.
  • Temporal — have a particular time component. Example: a reminder to check whether important security updates have been performed, or a scheduled dependency check that alerts on outdated libraries.

Static vs Dynamic

  • Static — fixed predefined acceptable values. Binary pass/fail (a unit test), or a threshold (latency must be < 200ms).
  • Dynamic — acceptable values depend on context. Acceptable latency might depend on actual system scale; security requirements might vary based on the regulatory environment.

Automated vs Manual

  • Automated — unit tests, deployment pipeline checks, stress tests, chaos engineering. Ideally as much automation as possible.
  • Manual — some things can't be automated (legal approval requirements, certain QA processes). Some things aren't automated yet. The goal is to push the boundary toward automation over time.

What fitness functions look like in practice

Fitness functions encompass existing engineering practices but also extend beyond them:

Category Examples Type
Architecture tests phpat (PHP/PHPStan) or ts-arch (TypeScript) rules checking component dependencies, layer violations, naming conventions, import directionality Atomic, triggered
Code metrics Cyclomatic complexity thresholds, afferent/efferent coupling limits Atomic, triggered
Contract tests API contract verification ensuring requirements are met Atomic, triggered
Security scanning Vulnerability scanning, licence compliance checks for open-source dependencies Atomic, triggered
Performance testing Load tests validating latency SLOs under expected concurrency Holistic, triggered
Monitoring & alerting p99 latency monitors, error rate thresholds, SLO compliance dashboards Atomic/holistic, continuous
Chaos engineering Netflix Simian Army — randomly terminating instances, availability zones, or entire regions Holistic, continuous
Security reviews Quarterly security audits, penetration testing Holistic, manual/temporal
Dependency freshness Scheduled checks for outdated libraries or security patches Atomic, temporal

The best fitness functions are automated and triggered: they give feedback at the point of change, not weeks later. Place them in the deployment pipeline. Fast atomic functions early, slow holistic functions later.

Deployment pipelines as the enforcement mechanism

Fitness functions only work if they're part of the delivery workflow. The deployment pipeline is where they live:

  1. Early stages — fast, atomic checks: architecture tests (phpat, ts-arch), code metrics, linting, security scanning, contract tests.
  2. Middle stages — integration and performance tests, holistic triggered functions.
  3. Later stages / production — continuous monitoring, chaos engineering, temporal reminders.

As Thoughtworks puts it: "creating the desired fitness functions — and including them in appropriate delivery pipelines — communicates these metrics as an important aspect of enterprise architecture."

The four layers of fitness (from NILUS)

A useful framing from practice splits fitness functions across four layers:

  1. Structural fitness — code dependencies, database access patterns, API contracts, service boundaries.
  2. Behavioural fitness — latency, resilience, throughput, consistency, recovery behaviour.
  3. Operational fitness — deployment independence, observability coverage, runbook readiness, SLO compliance.
  4. Semantic fitness — bounded context integrity, event naming quality, policy ownership, domain model consistency.

Most teams start at structural (the easiest to automate) and never reach semantic. But semantic fitness functions (checking that your domain model remains coherent as it evolves) are often the most valuable for long-lived systems.

Systems thinking

Dr. Russell Ackoff's quote captures the deeper point:

A system is never the sum of its parts. It is the product of the interaction of its parts.

Fitness functions that only measure individual components miss the point. The interesting failures happen at integration boundaries — between services, between teams, between intentions and reality. Holistic fitness functions (end-to-end latency, deployment frequency, change failure rate) capture what atomic ones cannot.

How I'm applying this

This connects directly to work I care about:

  • Platform modernisations I've designed and implemented were operational fitness: bringing reliability through automated deployment pipelines, observability and monitoring, and runbook readiness. I just called it "keeping things running."
  • ADRs capture the decisions. Fitness functions verify those decisions are still holding. Decisions and verification go hand in hand.
  • Kent Beck's Test Desiderata is itself a fitness function for test quality — a checklist of characteristics that tests should exhibit (isolated, deterministic, fast, behavioural, structure-insensitive, specific, predictive).
  • DORA metrics (deployment frequency, lead time, change failure rate, MTTR) are fitness functions for delivery capability.
  • Code health metrics (as described in the Loveholidays case from Tropeçando 120) are fitness functions that enabled their AI-first shift — they invested in code health metrics before adopting AI, which is exactly the fitness-function-first approach.
  • phpat (PHP, as a PHPStan extension) and ts-arch (TypeScript) — writing architecture rules as unit tests that run in CI is the purest implementation of triggered atomic fitness functions.

The pattern: define what matters, measure it, enforce it automatically, and revisit periodically. Architecture that can't be verified can't evolve — it can only decay.

Further reading


Part of my reading notes on Building Evolutionary Architectures (Ford, Parsons, Kua).

Categorias
Programming Technology

Building Evolutionary Architectures Notes

Notes

Chapter 1: Software Architecture

Despite our best efforts, software becomes harder to change over time. For a variety of reasons, the parts that comprise software systems defy easy modifications, becoming more brittle and intractable over time. Changes in software projects are usually driven by a reevaluation of functionality and/or scope. But another type of change occurs outside the control of architects and long-term planners. Though architects like to be able to strategically plan for the future, the constantly changing software development ecosystem makes that difficult. Since we can't avoid change, we need to exploit it.

— On Evolutionary Architecture

An evolutionary architecture supports guided, incremental changes across multiple dimensions.

— Definition of Evolutionary Architecture

Related: Ralph Johnson on Architecture (via Fowler, 2003)

These quotes from Ralph Johnson (from [[2026-04-24 - Martin Fowler - Who Needs an Architect|Who Needs an Architect?]]) are foundational to the ideas in this book:

"In most successful software projects, the expert developers working on that project have a shared understanding of the system design. This shared understanding is called 'architecture.' [...] the architecture only includes the components and interfaces that are understood by all the developers."

— Architecture as a social construct, not a diagram.

"There is no theoretical reason that anything is hard to change about software. If you pick any one aspect of software then you can make it easy to change, but we don't know how to make everything easy to change. Making something easy to change makes the overall system a little more complex, and making everything easy to change makes the entire system very complex. Complexity is what makes software hard to change. That, and duplication."

— The fundamental tension that evolutionary architectures try to navigate: change vs complexity.

"Software is not limited by physics, like buildings are. It is limited by imagination, by design, by organization. In short, it is limited by properties of people, not by properties of the world. 'We have met the enemy, and he is us.'"

— The constraint is us, not the technology.

Chapter 2: Fitness Functions

An evolutionary architecture supports guided, incremental change across multiple dimensions.

-- on FItness Functions, chapter 2

The fitness function protects the various archutectural characteristics required for the system. The specific architectural requirements differ greatly across systems and organizations, based on business drivers, technical capabilities, and a host of other factors. Some systems require intense security; others require significant throughput factors.

-- on Fitness Functions, chapter 2

A system is never the sum of its parts. It is the product of the interaction of its parts.

-- Dr. Russel Ackoff

Categorias
Tropeçando

Tropeçando 120

AI Management & Organizational Restructuring

The Foreman Problem: Managing Teams When Your Best Worker Isn't Human - Willian Correa

Every major technology shift invented a new management role. Steam power → foreman. Office computing → project manager. Internet → product manager. AI is doing the same, but this time the failure mode is invisible: confident, polished, wrong output. The new job is not directing effort but verifying that things that look like they're running actually are.

Who Will Be the Senior Engineers of 2035? - James Stanier

The traditional junior-to-senior pipeline is breaking: entry-level tech postings down 67% since 2022, junior employment down ~20%. Firms adopting AI saw junior employment fall 7.7% vs non-adopters. 54% of engineering leaders plan to hire fewer juniors.

Compound Engineering & Code Health

The Compounding Software Factory - Luca Rossi (Software Factory series, Part 3 of 3)

What causes teams to degrade: poor coding hygiene (bad testing, poor code health, missing abstractions), failure to capture knowledge (no ADRs, no playbooks, no snapshots), and building the wrong things.

AI Coding Meets Code Health - Stuart Caborn

Loveholidays' journey to becoming an AI-first engineering organization. Core thesis: code health is the foundation for successful AI adoption. By deliberately investing in code health metrics before adopting AI, they achieved 80+ deployments/month, 60% AI-written code, <1% change failure rate, all while maintaining elite code health.

Security & Infrastructure

The (In)security Landscape of AI-Powered GitHub Actions - Shay Berkovich

AI-powered GitHub Actions from vendors like OpenAI, Anthropic, and Google are now running in thousands of public workflows. Research found bypasses of non-default configurations letting any external attacker trigger AI execution, a novel secret exfiltration vector for dynamically-created credential files, and widespread misconfigurations in production workflows.

The Invisible Engineering Behind Lambda's Network - Werner Vogels

A decade-long story of invisible infrastructure engineering by Lambda's networking team.

Career & Token Economics

Tokenmaxxing Is the Budget Game Played With AI Tokens - Willian Correa

Tokenmaxxing — maximising AI token consumption for visibility — is the corporate "use it or lose it" budget game in a new currency. Meta's internal "Claudeonomics" leaderboard ranked 85K employees by token consumption; top user burned 281B tokens in 30 days.

Tools

Use Compose Watch

Docker bind volumes gets a supercharge. Compose Watch does not replace bind mounts but exists as a companion specifically suited to developing in containers.

More importantly, watch allows for greater granularity than is practical with a bind mount. Watch rules let you ignore specific files or entire directories within the watched tree.
For example, in a Node.js project, it's not recommended to sync the node_modules/ directory. Even though JavaScript is interpreted, npm packages can contain native code that is not portable across platforms.

Categorias
Miscelaneous

Geek

A "geek" is someone who is highly creative, highly technical, and highly attached to being both.

-- GeePaw Hill

Categorias
Programming

Introduce Parameter Object | Refactoring Patterns

This refactoring pattern involves grouping parameters that naturally go together into a single object. When you see a group of data items that regularly travel together, appearing in function after function, it's a sign they should be combined into a single object.

Check https://rafael.bernard-araujo.com/refactoring-patterns/introduce-parameter-object

There are PHP and Rust implemenation examples.

Categorias
Tropeçando

Tropeçando 119

How to Grow your Software Factory

Luca Rossi argues that the right measure of AI effectiveness isn't lines of code but leverage — how much output you get per unit of human input. Teams progress through three stages: writing full specs for everything, then encoding knowledge into shared rules (like AGENTS.md), and finally building reusable modules that enforce correctness by design.

The security case for serverless just got stronger

AI agents can now scan an entire open-source codebase for exploitable vulnerabilities in hours.

Frontier models carry the complete library of known bug classes in their weights. So you can simply point an AI agent at a codebase and tell it to find zero-days.

This isn't theoretical.

Yan Cui highlights that AI agents can now find real zero-days in open-source codebases at scale, shrinking the patch window from weeks to hours. Serverless and managed services have a structural advantage because AWS patches the runtime for you. The practical takeaways: eliminate long-lived AWS keys everywhere, treat LLM API keys like credentials, and scan your repos for exposed secrets.

Do not use secrets in environment variables and here's how to do it better

Every Layer of Review Makes You 10x Slower

Each approval layer adds 10x wall clock time, and AI can't fix that. It only speeds up the first step. Drawing on Deming and the Toyota Production System, the argument is that review layers hide root causes rather than fixing them. The memorable line: "The job of a code reviewer isn't to review code — it's to figure out how to obsolete their review comment, that whole class of comment, forever."

The common thread across all four: the bottleneck isn't writing code, it's the systems around it. Whether it's review layers, security patching, or AI leverage, the answer is the same: engineer quality into the system itself through tests, automation, modules, and clear interfaces, rather than adding layers of inspection after the fact.

Claude Code cache chaos creates quota complaints

Anthropic changed the prompt cache TTL from 1 hour to 5 minutes in March. Long, high-context sessions hit quota limits much faster. Pro users report as few as 2 prompts per 5 hours. Leaving your machine for >1 hour = full cache miss on the 1M token context. They're considering reducing the default to 400K tokens.

Token consumption matters more than ever. The next two tools address this from both ends.

Caveman — Output Token Compression

Constrains LLM output to minimal-token structures. Strips pleasantries and padding, keeps code and technical content. Up to 87% output token reduction. Paper shows brevity constraints improve accuracy by 26pp.

RTK (Rust Token Killer) — Input Token Compression

Intercepts shell command outputs (git, ls, grep, test runners, docker, AWS CLI — 100+ commands) and compresses them before they reach the LLM context. 60-90% input token reduction, < 10ms overhead.

Works with: Claude Code, Copilot, Gemini CLI, Codex, Cursor, Windsurf, Cline.

Categorias
Tropeçando

Tropeçando 118

Your AI Coding agent doesn’t know when to ask for help

Why do multi-agent coding systems fall apart on complex, real-world tasks?

How to Manage Context in AI Coding

Focus on building multiplayer, dynamic systems that provide the right information reliably, rather than crafting magical wording. Design workflows where AI can fetch what it needs automatically.

Value Object

When programming, I often find it's useful to represent things as a compound.

Range - Further Enterprise Application Architecture development

It's quite common to see comparisons where a value is checked against a range of values. Ranges are usually handled by a pair of values and you check against them both. Range instead uses a single object to represent the range as a whole, and then provides the relevant operations to test to see if values fall in the range and to compare ranges.

JDK 17 Memory Bloat in Containers: A Post-Mortem

I just love runtime upgrades. Runtime upgrade are very important. And they need careful planning. Not unusual that they teach us important lessons for the next upgrade.

When engineering teams modernize Java applications, the shift from JDK 8 to newer Long-Term Support (LTS) versions, such as JDK 11, 17, and soon 21, might seem straightforward at first. Since Java maintains backward compatibility, it's easy to assume that the runtime behavior will remain largely unchanged. However, that's far from reality.

My Fitbit Buzzed and I Understood Enshittification

My Fitbit started buzzing at me a year ago. “It looks like you’re exercising.”

Product development is also an exercise in human relationships. And when we reduce those relationships to metrics, we lose something essential. We lose the ability to say, “This would be rude.” We lose the ability to treat users like people instead of engagement vectors.

Using the Middleware Pattern to Extend PHP Libraries

PSR-15 did not invent middleware. But it showed the PHP community what a well-designed, typed middleware interface looks like. There is no reason to leave that idea at the HTTP layer.

If you maintain a PHP library with any non-trivial processing, consider building middleware support in from day one. Your users will thank you, and so will your future self.