← Clean Architecture ainda importa quando a IA escreve o código?
Clean Architecture ainda importa quando a IA escreve o código?
Português ↔ English
Código barato não significa software barato
Durante muito tempo, uma parte importante do custo de software estava na própria escrita do código. Era preciso transformar requisitos em implementação, percorrer arquivos, lembrar contratos, escrever testes, corrigir erros de sintaxe e repetir esse ciclo até a mudança ficar aceitável.
Coding agents mudaram essa relação.
Hoje um agente consegue ler uma tarefa, explorar um repositório, alterar vários arquivos, executar testes e preparar uma entrega. A consequência mais interessante não é simplesmente "programar mais rápido". É que a escrita do código deixou de ser o gargalo dominante em uma parte crescente do trabalho.
Isso cria uma tentação: se um modelo consegue gerar implementação rapidamente, talvez Clean Code, Clean Architecture, separação de responsabilidades e limites de dependência tenham perdido importância.
Eu penso justamente o contrário.
Quanto mais barato fica produzir código, mais caro fica aceitar código ruim sem perceber.
O problema se desloca. Antes eu precisava controlar principalmente o esforço de escrever. Agora preciso controlar o volume de mudança que entra no sistema, a coerência dessas mudanças e a facilidade de verificar se elas respeitam o que já existe.
Clean Architecture e Clean Code continuam úteis, mas eu não trataria nenhum dos dois como religião. Na era dos agentes, os princípios que sobrevivem são os que conseguem virar restrições legíveis, verificáveis e automatizáveis.
O que realmente permanece relevante
Quando falo em Clean Architecture aqui, não estou defendendo uma quantidade fixa de pastas, interfaces ou camadas.
O que continua valioso é algo mais simples:
- separar responsabilidades que mudam por motivos diferentes;
- impedir que regras centrais dependam diretamente de detalhes externos;
- manter contratos claros nas fronteiras;
- limitar direções de dependência;
- tornar efeitos colaterais explícitos;
- conseguir testar comportamento importante sem montar o sistema inteiro.
O mesmo vale para Clean Code.
Nomes claros, funções pequenas quando isso melhora compreensão, coesão, baixo acoplamento e ausência de duplicação continuam ajudando. Mas o objetivo não é produzir código que "pareça clean". O objetivo é reduzir ambiguidade para quem — humano ou agente — precisar entender e alterar aquilo depois.
Com IA, essa última parte ganha peso.
Um modelo trabalha a partir do contexto que consegue observar. Se um módulo mistura regra de negócio, acesso a banco, transformação de payload, autorização e chamadas externas na mesma unidade, o agente precisa inferir limites que o código não expressa.
Se esses limites estão claros, o trabalho fica mais previsível.
A grande mudança: arquitetura precisa ser executável
Documentar arquitetura sempre foi útil. Para coding agents, documentação sozinha é insuficiente.
A experiência publicada pela OpenAI em Harness engineering: leveraging Codex in an agent-first world é interessante justamente por isso. No experimento descrito, os agentes produziam todo o código do produto, e a equipe passou a investir fortemente em estrutura de repositório, ferramentas, testes, documentação e invariantes verificáveis.
Um dos pontos mais importantes do relato é a ideia de enforcing architecture and taste: não tentar controlar cada implementação, mas tornar certas regras arquiteturais obrigatórias.
Essa distinção é essencial.
Eu não quero dizer a um agente exatamente como escrever cada função. Quero garantir coisas como:
- domínio não importa diretamente adaptadores de infraestrutura;
- entrada externa é validada na fronteira;
- um módulo só acessa outro por contratos permitidos;
- efeitos destrutivos exigem validação explícita;
- testes relevantes precisam passar antes da entrega.
Isso é muito mais escalável do que uma coleção de instruções de estilo em um prompt.
Arquitetura passa a funcionar como um sistema de guardrails.
O agente amplifica tanto a boa quanto a má estrutura
Quando um desenvolvedor humano encontra uma base confusa, normalmente a velocidade cai. Ele precisa investigar, perguntar, testar hipóteses e formar um modelo mental.
Um coding agent também sofre com isso, mas existe uma diferença: ele consegue produzir muito código mesmo quando entendeu apenas parcialmente o sistema.
Esse é um risco novo de escala.
Um agente pode rapidamente:
- copiar um padrão ruim existente;
- criar uma abstração paralela porque não encontrou a anterior;
- atravessar uma fronteira de módulo porque o compilador permite;
- duplicar validações em locais diferentes;
- consertar um teste local enquanto introduz uma inconsistência arquitetural maior.
A capacidade de geração aumenta o raio de ação.
Por isso eu considero coesão e limites explícitos mais importantes, não menos.
Um módulo coeso dá ao agente uma área menor para raciocinar. Uma interface estável reduz possibilidades. Uma regra de dependência verificável transforma uma decisão arquitetural em feedback imediato.
Clean Code muda quando o autor pode ser descartável
Uma ideia que ficou mais evidente para mim com agentes é que o valor de Clean Code nunca esteve na estética do código.
Ele está no custo de leitura e mudança.
Se a maior parte da implementação for gerada por IA, eu me importo menos com quem digitou a linha e mais com perguntas como:
- consigo entender por que essa função existe?
- o nome revela a intenção?
- a regra está no lugar esperado?
- existe um teste que protege o comportamento?
- a próxima alteração exigirá conhecer cinco módulos desnecessariamente?
- consigo remover essa implementação sem desmontar o restante?
Isso muda inclusive a forma como eu avalio abstrações.
Uma abstração só vale a pena quando reduz carga cognitiva ou protege uma regra real. Se ela existe apenas porque uma arquitetura "bonita" diz que deveria existir, provavelmente virou custo.
O perigo do overengineering continua — e pode piorar
LLMs são muito bons em produzir estrutura.
Peça uma arquitetura "enterprise-ready" e, se você não limitar o escopo, é fácil receber interfaces, factories, repositories, use cases, DTOs, adapters e abstrações suficientes para resolver um problema que talvez precisasse de três arquivos.
A IA não eliminou o overengineering. Ela tornou o overengineering barato de gerar.
Isso é perigoso porque custo de criação e custo de manutenção são coisas diferentes.
Criar sete camadas leva segundos. Entender por que elas existem seis meses depois continua custando tempo.
Minha regra prática é: a fronteira precisa ter uma razão observável.
Eu criaria uma separação quando pelo menos uma destas condições aparece:
- existe uma dependência externa que pode mudar;
- existe regra de negócio que precisa sobreviver à infraestrutura;
- existe necessidade real de testar sem o mundo externo;
- dois grupos de comportamento mudam por razões diferentes;
- existe risco de segurança, consistência ou irreversibilidade na fronteira;
- existe necessidade clara de substituir uma implementação.
Fora disso, simplicidade ganha.
Um exemplo de limite útil
Imagine uma aplicação que recebe uma solicitação para publicar conteúdo.
Uma implementação rápida pode colocar autenticação, validação, geração de arquivo e persistência numa única função.
Funciona.
Mas existe uma fronteira natural:
Request
↓
Authenticate
↓
Validate publication
↓
Prepare immutable publication files
↓
Commit atomically
↓
Return deployment status
Essa separação não precisa virar seis frameworks internos.
O importante é que as responsabilidades sejam visíveis e que o passo "commit atomically" não consiga receber um conjunto incompleto de arquivos.
Para um agente, isso cria um caminho de trabalho claro. Ele pode alterar serialização sem mexer em autenticação. Pode testar validação sem chamar GitHub. Pode trocar o mecanismo de persistência sem reescrever a regra editorial.
É Clean Architecture aplicada como redução de espaço de erro, não como cerimônia.
Testes se tornam parte da arquitetura
Com geração de código em alta velocidade, testes deixam de ser apenas uma rede de segurança posterior.
Eles passam a funcionar como uma linguagem executável do sistema.
Um prompt pode dizer "não quebre os slugs existentes". Um teste pode provar isso.
Uma documentação pode dizer "as três traduções devem ser publicadas juntas". Um teste pode rejeitar qualquer publicação parcial.
Uma convenção pode dizer "domínio não importa infraestrutura". Uma regra estática pode falhar o build quando isso acontecer.
Quanto mais dessas decisões viram feedback automático, menos o agente precisa adivinhar.
É exatamente por isso que a discussão atual sobre agentes está cada vez menos centrada apenas no modelo. A própria OpenAI descreve o harness como a combinação de contexto, ferramentas, ambiente e loops de execução. O modelo continua importante, mas confiabilidade aparece na interação entre modelo e sistema de controle.
Legibilidade para agentes é uma nova qualidade arquitetural
Nós sempre falamos de legibilidade para humanos. Agora existe outra pergunta:
o repositório é legível para um agente?
Isso não significa escrever código para agradar um LLM. Significa reduzir conhecimento implícito.
Algumas coisas ajudam bastante:
- nomes de diretórios previsíveis;
- documentação próxima do código;
- comandos claros para testar e validar;
- exemplos reais de padrões aceitos;
- schemas e tipos explícitos;
- poucas formas diferentes de fazer a mesma coisa;
- mensagens de erro úteis;
- dependências direcionais que podem ser verificadas;
- arquivos de instrução curtos e específicos.
No DevAgent, uma das ideias que considero mais importantes é o agente entregar pelo fluxo normal de engenharia: tarefa, alteração, checks e pull request revisável.
Isso importa porque autonomia não deveria significar ausência de processo.
O que eu manteria de Clean Architecture em 2026
Se eu tivesse que reduzir tudo a um conjunto pequeno de regras para projetos com muita geração por IA, seria este:
1. Fronteiras antes de camadas
Não comece desenhando quatro anéis. Comece identificando o que não deveria conhecer o quê.
2. Contratos explícitos nas entradas
Dados vindos de usuário, rede, modelo ou ferramenta são externos. Valide na fronteira.
3. Domínio protegido de detalhes voláteis
Framework, banco e fornecedor de IA mudam mais rápido que as regras centrais do produto.
4. Invariantes automatizados
Se uma regra arquitetural importa, tente transformá-la em teste, lint, tipo, schema ou check de CI.
5. Abstrações justificadas por mudança
Não crie interface porque "é o correto". Crie quando ela protege uma variação real.
6. Código fácil de apagar
Software gerado rapidamente também precisa ser substituído rapidamente. Baixo acoplamento ajuda muito aqui.
7. Feedback rápido
Agentes precisam descobrir erros durante a execução, não depois que a mudança já se espalhou.
E o que eu descartaria
Eu descartaria qualquer interpretação de Clean Code ou Clean Architecture que exija estrutura sem benefício verificável.
Não vejo valor em:
- uma interface com uma única implementação e nenhuma fronteira relevante;
- dezenas de arquivos para representar uma operação trivial;
- abstrações genéricas antes de existir repetição real;
- camadas cujo único papel é repassar parâmetros;
- proibição dogmática de funções longas mesmo quando a divisão piora o entendimento;
- regras de estilo tratadas como se fossem regras de domínio.
IA aumenta a necessidade de disciplina, mas também aumenta a necessidade de pragmatismo.
Se um agente consegue criar complexidade em segundos, a equipe precisa ficar ainda melhor em dizer não à complexidade desnecessária.
A minha conclusão
Clean Architecture e Clean Code não ficaram obsoletos porque a IA escreve código.
O que ficou obsoleto é tratar esses conceitos como uma coleção fixa de formas de escrever software.
Os princípios úteis continuam fortes: coesão, baixo acoplamento, separação de responsabilidades, dependências direcionais, contratos explícitos, legibilidade e testabilidade.
A diferença é que agora eu quero transformar esses princípios em coisas que um agente consiga observar e que uma máquina consiga verificar.
Quando código era caro de escrever, arquitetura ajudava a organizar o trabalho humano.
Quando código fica barato de gerar, arquitetura ajuda a limitar a entropia que essa geração pode produzir.
Talvez essa seja a adaptação mais importante: menos preocupação em fazer o código parecer "clean" e mais preocupação em construir um sistema no qual tanto humanos quanto agentes tenham dificuldade de fazer a coisa errada.
Referências
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.