← ¿Clean Architecture sigue importando cuando la IA escribe el código?
¿Clean Architecture sigue importando cuando la IA escribe el código?
Español ↔ English
Código barato no significa software barato
Durante mucho tiempo, una parte importante del coste del software estaba en escribir el código. Había que transformar requisitos en implementación, recorrer archivos, recordar contratos, escribir tests, corregir errores y repetir el ciclo hasta que el cambio fuese aceptable.
Los coding agents están cambiando esa relación.
Hoy un agente puede leer una tarea, explorar un repositorio, modificar varios archivos, ejecutar tests y preparar una entrega. La consecuencia interesante no es solo "programar más rápido". Es que escribir código está dejando de ser el cuello de botella dominante en una parte cada vez mayor del trabajo de ingeniería.
Eso crea una tentación: si un modelo puede generar implementación rápidamente, quizá Clean Code, Clean Architecture, la separación de responsabilidades y los límites de dependencia importen menos.
Creo que ocurre lo contrario.
Cuanto más barato resulta producir código, más caro puede ser aceptar código malo sin darnos cuenta.
El problema se desplaza. Antes gran parte del reto era controlar el esfuerzo necesario para escribir software. Ahora también necesitamos controlar el volumen de cambios que entra al sistema, la coherencia de esos cambios y la facilidad con la que podemos verificar que respetan lo que ya existe.
Clean Architecture y Clean Code siguen siendo útiles, pero no trataría ninguno como religión. En un flujo con agentes, los principios que sobreviven son los que pueden convertirse en restricciones legibles, verificables y automatizables.
Lo que realmente sigue siendo útil
Cuando hablo de Clean Architecture aquí, no defiendo una cantidad fija de carpetas, interfaces o capas.
Lo que sigue teniendo valor es más simple:
- separar responsabilidades que cambian por motivos distintos;
- evitar que las reglas centrales dependan directamente de detalles externos;
- mantener contratos claros en las fronteras;
- limitar las direcciones de dependencia;
- hacer explícitos los efectos secundarios;
- poder probar comportamiento importante sin montar el sistema entero.
Lo mismo vale para Clean Code.
Nombres claros, funciones pequeñas cuando mejoran la comprensión, cohesión, bajo acoplamiento y evitar duplicación innecesaria siguen ayudando. Pero el objetivo no es producir código que simplemente parezca clean. El objetivo es reducir la ambigüedad para quien —humano o agente— tenga que entenderlo y modificarlo después.
Con IA, esa última parte gana importancia.
Un modelo trabaja con el contexto que puede observar. Si un módulo mezcla reglas de negocio, acceso a base de datos, transformación de payload, autorización y llamadas externas, el agente tiene que inferir fronteras que el propio código no expresa.
Cuando esas fronteras son claras, el trabajo se vuelve más predecible.
El gran cambio: la arquitectura tiene que ser ejecutable
Documentar arquitectura siempre ha sido útil. Para coding agents, la documentación por sí sola no basta.
La experiencia publicada por OpenAI en Harness engineering: leveraging Codex in an agent-first world es interesante precisamente por eso. En el experimento descrito, los agentes escribían el código del producto y el equipo de ingeniería invertía mucho en estructura del repositorio, herramientas, tests, documentación e invariantes verificables.
Una de las ideas más importantes del relato es enforcing architecture and taste: no controlar cada detalle de implementación, sino hacer obligatorias ciertas reglas arquitectónicas.
La diferencia es fundamental.
No quiero decirle a un agente exactamente cómo escribir cada función. Quiero garantizar cosas como:
- el dominio no importa directamente adaptadores de infraestructura;
- la entrada externa se valida en la frontera;
- los módulos acceden unos a otros solo mediante contratos permitidos;
- los efectos destructivos requieren validación explícita;
- los tests relevantes deben pasar antes de entregar.
Eso escala mejor que una colección enorme de instrucciones de estilo dentro de un prompt.
La arquitectura pasa a funcionar como un sistema de guardrails.
El agente amplifica tanto la buena como la mala estructura
Cuando un desarrollador humano encuentra una base confusa, normalmente baja la velocidad. Tiene que investigar, preguntar, probar hipótesis y construir un modelo mental.
Un coding agent sufre la misma ambigüedad, pero con una diferencia importante: puede producir mucho código aunque solo haya entendido parcialmente el sistema.
Ese es un nuevo riesgo de escala.
Un agente puede rápidamente:
- copiar un patrón malo ya existente;
- crear una abstracción paralela porque no encontró la anterior;
- cruzar una frontera de módulo porque el compilador lo permite;
- duplicar validaciones en distintos lugares;
- arreglar un test local mientras introduce una inconsistencia arquitectónica mayor.
La capacidad de generación aumenta el radio de impacto.
Por eso considero la cohesión y los límites explícitos más importantes, no menos.
Un módulo cohesivo le da al agente una superficie menor para razonar. Una interfaz estable reduce posibilidades. Una regla de dependencia verificable convierte una decisión arquitectónica en feedback inmediato.
Clean Code cambia cuando el autor puede ser descartable
Algo que los agentes dejan más claro es que el valor de Clean Code nunca estuvo en la estética.
Está en el coste de leer y cambiar software.
Si gran parte de la implementación la genera IA, me importa menos quién escribió la línea y más preguntas como:
- ¿puedo entender por qué existe esta función?
- ¿el nombre revela la intención?
- ¿la regla está donde espero encontrarla?
- ¿hay un test que proteja el comportamiento?
- ¿el próximo cambio exigirá conocer cinco módulos sin relación?
- ¿puedo eliminar esta implementación sin desmontar el resto?
Eso cambia también la forma de evaluar abstracciones.
Una abstracción merece su coste cuando reduce carga cognitiva o protege una regla real. Si existe solo porque una arquitectura "bonita" dice que debería existir, probablemente sea sobrecarga.
El overengineering sigue siendo peligroso — y la IA puede empeorarlo
Los LLMs son muy buenos produciendo estructura.
Pide una arquitectura "enterprise-ready" sin limitar el alcance y es fácil recibir interfaces, factories, repositories, use cases, DTOs y adapters suficientes para resolver un problema que quizá necesitaba tres archivos.
La IA no eliminó el overengineering. Hizo barato generarlo.
Eso importa porque el coste de crear y el coste de mantener son cosas distintas.
Generar siete capas lleva segundos. Entender por qué existen seis meses después sigue costando tiempo.
Mi regla práctica es: una frontera necesita una razón observable para existir.
Introduciría separación cuando al menos una de estas condiciones aparece:
- existe una dependencia externa que puede cambiar;
- la lógica de negocio debe sobrevivir a cambios de infraestructura;
- hace falta probar comportamiento importante sin sistemas externos;
- dos grupos de comportamiento cambian por razones distintas;
- existe riesgo de seguridad, consistencia o irreversibilidad en la frontera;
- sustituir una implementación es una necesidad real.
Fuera de esos casos, gana la simplicidad.
Un límite útil en la práctica
Imagina una aplicación que recibe una solicitud para publicar contenido.
Una implementación rápida puede colocar autenticación, validación, generación de archivos y persistencia en una única función.
Funciona.
Pero existe un flujo natural:
Request
↓
Authenticate
↓
Validate publication
↓
Prepare immutable publication files
↓
Commit atomically
↓
Return deployment status
Esta separación no necesita convertirse en seis frameworks internos.
Lo importante es que las responsabilidades sean visibles y que el paso "commit atomically" no pueda recibir un conjunto incompleto de archivos.
Para un agente, eso crea un camino claro. Puede cambiar la serialización sin tocar autenticación. Puede probar validación sin llamar a GitHub. Puede cambiar persistencia sin reescribir reglas editoriales.
Eso es Clean Architecture aplicada como reducción del espacio de error, no como ceremonia.
Los tests se convierten en parte de la arquitectura
Con generación de código a gran velocidad, los tests dejan de ser solo una red de seguridad posterior.
Se convierten en un lenguaje ejecutable del sistema.
Un prompt puede decir "no rompas los slugs existentes". Un test puede demostrarlo.
La documentación puede decir "las tres traducciones deben publicarse juntas". Un test puede rechazar una publicación parcial.
Una convención puede decir "el dominio no importa infraestructura". Una regla estática puede romper el build cuando ocurra.
Cuantas más decisiones arquitectónicas se conviertan en feedback automático, menos necesita adivinar el agente.
Por eso la conversación actual sobre agentes trata cada vez menos solo del modelo. OpenAI describe el harness en términos de contexto, herramientas, entorno y loops de ejecución. El modelo importa, pero la confiabilidad aparece en la interacción entre el modelo y su sistema de control.
La legibilidad para agentes es una nueva cualidad arquitectónica
Siempre hemos hablado de legibilidad para humanos. Ahora aparece otra pregunta:
¿el repositorio es legible para un agente?
Eso no significa escribir código para agradar a un LLM. Significa reducir conocimiento implícito.
Ayudan especialmente:
- nombres de directorios previsibles;
- documentación cerca del código;
- comandos claros para probar y validar;
- ejemplos reales de patrones aceptados;
- schemas y tipos explícitos;
- pocas formas distintas de resolver el mismo problema;
- mensajes de error útiles;
- direcciones de dependencia verificables;
- archivos de instrucciones cortos y específicos.
En DevAgent, una idea que considero especialmente importante es que el agente entrega mediante el flujo normal de ingeniería: tarea, cambios, checks y un pull request revisable.
Autonomía no debería significar ausencia de proceso.
Lo que conservaría de Clean Architecture en 2026
Si tuviera que reducir todo a pocas reglas para proyectos con mucha generación por IA, conservaría estas:
1. Fronteras antes que capas
No empieces dibujando cuatro círculos. Empieza identificando qué no debería conocer a qué.
2. Contratos explícitos en las entradas
Todo lo que venga de usuarios, red, modelos o herramientas es externo. Valídalo en la frontera.
3. Protege el dominio de detalles volátiles
Frameworks, bases de datos y proveedores de IA cambian más rápido que las reglas centrales del producto.
4. Automatiza invariantes
Si una regla arquitectónica importa, intenta convertirla en test, lint, tipo, schema o check de CI.
5. Justifica abstracciones mediante cambio real
No crees una interfaz porque supuestamente "es lo correcto". Créala cuando proteja una variación real.
6. Haz que el código sea fácil de borrar
El software generado rápidamente también tiene que poder sustituirse rápidamente. El bajo acoplamiento ayuda mucho.
7. Mantén feedback rápido
Los agentes necesitan descubrir errores durante la ejecución, no después de que el cambio se haya propagado.
Lo que descartaría
Descartaría cualquier interpretación de Clean Code o Clean Architecture que exija estructura sin beneficio verificable.
Veo poco valor en:
- una interfaz con una sola implementación y ninguna frontera relevante;
- decenas de archivos para representar una operación trivial;
- abstracciones genéricas antes de que exista repetición real;
- capas cuyo único trabajo es reenviar parámetros;
- prohibiciones dogmáticas de funciones largas cuando dividirlas empeora la claridad;
- preferencias de estilo tratadas como si fueran reglas de dominio.
La IA aumenta la necesidad de disciplina, pero también aumenta la necesidad de pragmatismo.
Si un agente puede crear complejidad en segundos, el equipo tiene que ser todavía mejor diciendo no a complejidad innecesaria.
Mi conclusión
Clean Architecture y Clean Code no quedaron obsoletos porque la IA escriba código.
Lo que quedó obsoleto es tratar esos conceptos como una colección fija de formas de escribir software.
Los principios útiles siguen fuertes: cohesión, bajo acoplamiento, separación de responsabilidades, dependencias direccionales, contratos explícitos, legibilidad y testabilidad.
La diferencia es que ahora quiero transformar esos principios en cosas que un agente pueda observar y una máquina pueda verificar.
Cuando escribir código era caro, la arquitectura ayudaba a organizar el trabajo humano.
Cuando el código se vuelve barato de generar, la arquitectura ayuda a limitar la entropía que esa generación puede producir.
Quizá esa sea la adaptación más importante: menos preocupación por hacer que el código parezca clean y más preocupación por construir un sistema donde tanto humanos como agentes tengan difícil hacer lo incorrecto.
Referencias
Cheap code does not mean cheap software
For a long time, a meaningful part of software cost was the act of writing code itself. Requirements had to become implementation, files had to be explored, contracts remembered, tests written, syntax fixed, and the loop repeated until the change was acceptable.
Coding agents are changing that relationship.
An agent can now read a task, inspect a repository, modify several files, run tests, and prepare a delivery. The interesting consequence is not simply "faster programming." It is that writing code is becoming less dominant as the bottleneck in a growing part of engineering work.
That creates an obvious temptation: if a model can generate implementation quickly, maybe Clean Code, Clean Architecture, separation of concerns, and dependency boundaries matter less.
I think the opposite is closer to reality.
The cheaper code becomes to produce, the more expensive it becomes to accept bad code without noticing.
The problem moves. Before, a large part of the challenge was controlling the effort required to write software. Now we also need to control the volume of change entering the system, the coherence of those changes, and how easily we can verify that they respect what already exists.
Clean Architecture and Clean Code are still useful, but I would not treat either as a religion. In an agent-heavy workflow, the principles that survive are the ones that can become legible, enforceable, and automatable constraints.
What actually remains useful
When I say Clean Architecture here, I am not defending a fixed number of folders, interfaces, or layers.
What remains valuable is simpler:
- separate responsibilities that change for different reasons;
- keep core rules from directly depending on external details;
- keep contracts clear at boundaries;
- limit dependency directions;
- make side effects explicit;
- test important behavior without assembling the whole system.
The same applies to Clean Code.
Clear names, small functions when they improve comprehension, cohesion, low coupling, and avoiding unnecessary duplication still help. But the goal is not to produce code that merely looks clean. The goal is to reduce ambiguity for whoever — human or agent — has to understand and change it next.
With AI, that last part becomes even more important.
A model works from the context it can observe. If a module mixes business rules, database access, payload transformation, authorization, and external calls in one unit, the agent has to infer boundaries that the code itself does not express.
When those boundaries are explicit, the work becomes more predictable.
The major change: architecture has to become executable
Architecture documentation has always been useful. For coding agents, documentation alone is not enough.
OpenAI's Harness engineering: leveraging Codex in an agent-first world is interesting precisely because of this. In the experiment described there, agents wrote the product's code, while the engineering team invested heavily in repository structure, tools, tests, documentation, and enforceable invariants.
One of the most important ideas in that report is enforcing architecture and taste: do not micromanage every implementation, but make certain architectural rules mandatory.
That distinction matters.
I do not want to tell an agent exactly how to write every function. I want guarantees such as:
- domain code does not directly import infrastructure adapters;
- external input is validated at the boundary;
- modules access each other only through allowed contracts;
- destructive effects require explicit validation;
- relevant tests must pass before delivery.
That scales much better than a long collection of style instructions in a prompt.
Architecture becomes a system of guardrails.
Agents amplify good structure and bad structure
When a human developer meets a confusing codebase, velocity usually drops. They investigate, ask questions, test hypotheses, and gradually build a mental model.
A coding agent suffers from the same ambiguity, but with one important difference: it can still produce a lot of code after only partially understanding the system.
That is a new scaling risk.
An agent can quickly:
- copy an existing bad pattern;
- build a parallel abstraction because it failed to find the existing one;
- cross a module boundary because the compiler allows it;
- duplicate validation in different places;
- fix a local test while introducing a larger architectural inconsistency.
Generation capacity increases the blast radius.
That is why I consider cohesion and explicit boundaries more important, not less.
A cohesive module gives the agent a smaller reasoning surface. A stable interface reduces the number of possibilities. An enforceable dependency rule turns an architectural decision into immediate feedback.
Clean Code changes when the author is disposable
One thing agents make clearer is that the value of Clean Code was never about code aesthetics.
It is about the cost of reading and changing software.
If most implementation is generated by AI, I care less about who typed the line and more about questions such as:
- can I understand why this function exists?
- does the name reveal intent?
- is the rule in the place where I expect it?
- is there a test protecting the behavior?
- will the next change require knowledge of five unrelated modules?
- can I remove this implementation without taking the rest apart?
This also changes how I evaluate abstractions.
An abstraction earns its cost when it reduces cognitive load or protects a real rule. If it exists only because a "beautiful" architecture says it should, it is probably overhead.
Overengineering is still dangerous — and AI can make it worse
LLMs are very good at producing structure.
Ask for an "enterprise-ready architecture" without limiting scope and it is easy to receive enough interfaces, factories, repositories, use cases, DTOs, and adapters to solve a problem that might have needed three files.
AI did not eliminate overengineering. It made overengineering cheap to generate.
That matters because creation cost and maintenance cost are different things.
Generating seven layers takes seconds. Understanding why they exist six months later still costs time.
My practical rule is: a boundary needs an observable reason to exist.
I would introduce separation when at least one of these is true:
- an external dependency is likely to change;
- business logic should survive infrastructure replacement;
- meaningful behavior needs to be tested without external systems;
- two groups of behavior change for different reasons;
- security, consistency, or irreversible effects exist at the boundary;
- replacing an implementation is a real requirement.
Outside those cases, simplicity wins.
A useful boundary in practice
Imagine an application receiving a request to publish content.
A quick implementation could put authentication, validation, file generation, and persistence in one function.
It works.
But there is a natural flow:
Request
↓
Authenticate
↓
Validate publication
↓
Prepare immutable publication files
↓
Commit atomically
↓
Return deployment status
This separation does not need to become six internal frameworks.
The important part is that responsibilities are visible and that the "commit atomically" step cannot receive an incomplete set of files.
For an agent, this creates a clear working path. It can change serialization without touching authentication. It can test validation without calling GitHub. It can replace persistence without rewriting editorial rules.
That is Clean Architecture used as a reduction of the error surface, not as ceremony.
Tests become part of the architecture
With high-speed code generation, tests are no longer only a safety net after implementation.
They become an executable language for the system.
A prompt can say "do not break existing slugs." A test can prove it.
Documentation can say "all three translations must be published together." A test can reject partial publication.
A convention can say "domain does not import infrastructure." A static rule can fail the build when it happens.
The more architectural decisions become automatic feedback, the less the agent has to guess.
This is also why current agent engineering discussions are increasingly about more than model choice. OpenAI describes the harness in terms of context, tools, environments, and execution loops. The model matters, but reliability emerges from the interaction between the model and its control system.
Agent legibility is becoming an architectural quality
We have always talked about readability for humans. Now there is another question:
is the repository legible to an agent?
That does not mean writing code to please an LLM. It means reducing implicit knowledge.
Useful properties include:
- predictable directory names;
- documentation close to the code it describes;
- clear commands for testing and validation;
- real examples of accepted patterns;
- explicit schemas and types;
- few competing ways to solve the same problem;
- useful error messages;
- enforceable dependency directions;
- short and specific instruction files.
In DevAgent, one idea I consider especially important is that the agent delivers through the normal engineering workflow: task, code changes, checks, and a reviewable pull request.
Autonomy should not mean absence of process.
What I would keep from Clean Architecture in 2026
If I had to reduce the idea to a small set of rules for projects with heavy AI-assisted development, I would keep these:
1. Boundaries before layers
Do not start by drawing four circles. Start by identifying what should not know about what.
2. Explicit contracts at inputs
Anything coming from users, networks, models, or tools is external. Validate it at the boundary.
3. Protect the domain from volatile details
Frameworks, databases, and AI providers change faster than the product's central rules.
4. Automate invariants
If an architectural rule matters, try to turn it into a test, lint rule, type, schema, or CI check.
5. Justify abstractions through change
Do not create an interface because it is supposedly "correct." Create it when it protects a real variation.
6. Make code easy to delete
Software generated quickly must also be replaceable quickly. Low coupling helps enormously.
7. Keep feedback fast
Agents need to discover mistakes during execution, not after the change has spread through the codebase.
What I would discard
I would discard any interpretation of Clean Code or Clean Architecture that demands structure without measurable benefit.
I see little value in:
- an interface with one implementation and no meaningful boundary;
- dozens of files representing a trivial operation;
- generic abstractions before real repetition exists;
- layers whose only job is forwarding parameters;
- dogmatic bans on long functions even when splitting them reduces clarity;
- style preferences treated as if they were domain rules.
AI increases the need for discipline, but it also increases the need for pragmatism.
If an agent can create complexity in seconds, the team has to become even better at saying no to unnecessary complexity.
My conclusion
Clean Architecture and Clean Code did not become obsolete because AI writes code.
What became obsolete is treating those ideas as a fixed collection of shapes for writing software.
The useful principles remain strong: cohesion, low coupling, separation of concerns, directional dependencies, explicit contracts, readability, and testability.
The difference is that now I want to turn those principles into things an agent can observe and a machine can verify.
When code was expensive to write, architecture helped organize human work.
When code becomes cheap to generate, architecture helps limit the entropy that generation can produce.
That may be the most important adaptation: less concern with making code look clean, and more concern with building a system where both humans and agents have a hard time doing the wrong thing.