
Produtos gratuitos e pagos para transformar ideias em uma base que você consegue executar.
13 produtos disponíveisContinue explorando tópicos similares

Resenha crítica de Clean Code: ideias centrais, um exemplo de frete, limitações e um roteiro para aplicar o livro sem dogmatismo.
448 commits no CLI, 152 no app, 268 no laboratório de modelo, 67 arquivos de ADR para 60 números e nenhum modelo promovido. O fechamento da série, só com dados reais.
Uma resposta com 'if n == 20: return 6765' passa em todos os testes de Fibonacci. No lemon-model ela recebe nota zero. Este post mostra o resto do sistema que impede hype de virar release.
Checklist de 47 pontos para encontrar bugs, riscos de segurança e problemas de performance antes do lançamento.
Templates testados em produção, usados por desenvolvedores. Economize semanas de setup no seu próximo projeto.
English summary: Open/Closed is not about freezing code forever. It is about moving change to explicit extension points so new requirements do not reopen the same module.
Resumo em português: OCP não manda parar de editar código. Ele manda parar de editar o mesmo arquivo toda vez que surge uma variação previsível.
as propO arquivo não quebra de uma vez.
Ele vai sendo aberto.
Cada nova exceção pede um if.
Cada nova variação pede um variant.
Cada novo caso especial pede "só mais uma prop".
No começo, isso parece produtividade.
Depois, vira retrabalho caro.
Depois, vira medo de mexer.
Foi assim em um Button.tsx com 18 props booleanas.
Foi assim em um service com regras espalhadas em três camadas.
Foi assim em um grid de produto que mudou de layout quatro vezes no trimestre.
O problema nunca foi a mudança.
O problema foi reabrir a mesma peça estrutural para acomodar toda mudança.
OCP existe para separar essas duas coisas. Ele não tenta matar a evolução. Ele tenta impedir que a evolução destrua o desenho original. Quando você cria um ponto de extensão claro, a mudança deixa de ser invasiva. Quando você não cria, o código passa a crescer por infiltração.
O ponto de virada é simples. Se a próxima variação exigir editar o núcleo, o núcleo ainda não está fechado do jeito certo. Se a próxima variação puder entrar por composição, o sistema está saudável. Essa diferença é o que salva componentes, APIs e time de virar um poço de exceções.
A definição clássica é conhecida. Entidades devem estar abertas para extensão e fechadas para modificação. Na prática, isso significa uma coisa mais concreta. Você define o comportamento estável. Você isola as partes que mudam. Você deixa as mudanças entrarem por contratos explícitos.
OCP não é uma regra sobre quantidade de linhas. Não é uma regra sobre classes. Não é uma regra sobre arquitetura "bonita". É uma regra sobre previsibilidade da mudança.
O módulo principal precisa continuar confiável. O comportamento base não deve ser reescrito sempre que surgem variações. As variações devem aparecer como implementações alternativas, slots, handlers, estratégias ou plugins. Esse é o coração da ideia.
Em um frontend, o núcleo pode ser um componente raiz. Em um backend, o núcleo pode ser um caso de uso. Em um design system, o núcleo pode ser uma primitive. Em todos os casos, a pergunta é a mesma. Como adiciono comportamento sem quebrar o comportamento existente?
OCP não quer dizer "nunca editar código existente". Se o contrato central está errado, você deve editar. Se o modelo mental mudou, você deve editar. Se houve aprendizado real, você deve refatorar. O que OCP combate é editar o núcleo por qualquer motivo trivial.
OCP também não quer dizer "criar abstração cedo demais". Abstração prematura é outro tipo de dívida. Quando você inventa extensões sem caso de uso, você complica o simples. Quando você cria interfaces sem variação real, você fabrica burocracia.
OCP não é sinônimo de herança. Herança pode quebrar o princípio com facilidade. Se o subtipo precisa de precondições novas ou ignora comportamento base, você não tem substituição limpa. Você tem um contrato mentiroso.
OCP também não exige framework. Você não precisa de uma arquitetura esotérica para aplicá-lo. Você precisa de fronteiras claras. Você precisa de nomes bons. Você precisa de módulos pequenos o bastante para mudar sem medo.
Se o arquivo cresce toda vez que surge uma nova regra, há cheiro de problema.
Se o mesmo componente acumula UI, regra e acesso a dados, há cheiro de problema.
Se o time responde a demanda com if novo em vez de contrato novo, há cheiro de problema.
Se a variação aparece como boolean atrás de boolean, há cheiro de problema.
Se o teste quebra por detalhe irrelevante, há cheiro de problema.
Alguns sinais são ainda mais explícitos.
O git blame vira uma lista confusa.
O snapshot vira campo minado.
O componente precisa de 10 props para fazer o básico.
A documentação fica maior que a implementação.
A expansão ficou mais cara que o componente em si.
Quando isso acontece, o problema não é só técnico. É cognitivo. O time perde o mapa. Cada pessoa passa a entender o componente de uma forma. Sem contrato, toda extensão vira aposta.
Os padrões mais úteis não são mágicos. Eles só empurram a variação para fora do núcleo. Os cinco mais confiáveis são estes.
as prop.Cada um resolve um tipo de variação.
Slots resolvem composição visual.
Render props resolvem política de renderização.
as prop resolve semântica e tag nativa.
Strategies resolvem comportamento alternativo.
Registry resolve extensões descobertas em runtime ou por configuração.
O ponto comum é o mesmo. Você não edita o coração para cada caso novo. Você cria um encaixe.
Slots funcionam bem quando o problema é estrutural. Em vez de um componente receber dezenas de booleanos, ele recebe partes. Cada parte cumpre um papel. O núcleo monta a composição. O consumidor escolhe o arranjo.
import { createContext, ReactNode, useContext } from "react";
const CardContext = createContext(false);
export function Card({ children }: { children: ReactNode }) {
return (
<section className="card">
<CardContext.Provider value={true}>{children}</CardContext.Provider>
</section>
);
}
Card.Header = function CardHeader({ children }: { children: ReactNode }) {
const inside = useContext(CardContext);
if (!inside) throw new Error("Card.Header must be used inside Card");
return <header className="card-header">{children}</header>;
};
Card.Body = function CardBody({ children }: { children: ReactNode }) {
return <div className="card-body">{children}</div>;
};
Card.Footer = function CardFooter({ children }: { children: ReactNode }) {
return <footer className="card-footer">{children}</footer>;
};
O benefício aqui é direto.
Se você quiser adicionar um badge, cria um slot novo.
Se quiser adicionar um action area, cria outro slot.
O Card raiz não precisa crescer em if.
O contrato continua estável.
Esse padrão é forte porque reduz a pressão por props booleanas. O design system cresce com partes, não com flags. Isso deixa a API mais previsível. E previsibilidade é uma forma concreta de OCP.
Render props são úteis quando a variação está na política, não na estrutura. O componente sabe buscar dados. O consumidor decide como renderizar. O núcleo expõe estado. O uso escolhe a forma.
type QueryState<T> = {
data: T | null;
loading: boolean;
error: string | null;
};
type DataViewProps<T> = {
state: QueryState<T>;
children: (state: QueryState<T>) => React.ReactNode;
};
export function DataView<T>({ state, children }: DataViewProps<T>) {
return <>{children(state)}</>;
}
Esse desenho é bom quando a lógica é estável. Você não quer editar um componente de dados toda vez que a tela muda. Você quer trocar a visão. No fundo, a tela passa a ser extensão. O núcleo fica fechado.
Headless components fazem algo parecido. Eles expõem estado e ações. Eles não escolhem a UI. Isso faz muito sentido em listas, filtros, menus, tabelas e fluxos de formulário.
as propPolimorfismo com as prop resolve uma dor específica.
O comportamento visual é o mesmo.
A semântica muda.
Às vezes o elemento precisa ser button.
Às vezes precisa ser a.
Às vezes precisa ser label.
type PolymorphicProps<C extends React.ElementType, P> = P &
{ as?: C } &
Omit<React.ComponentPropsWithoutRef<C>, keyof P>;
type TextProps = {
tone: "default" | "muted" | "strong";
};
export function Text<C extends React.ElementType = "p">(
{ as, tone, children, ...rest }: PolymorphicProps<C, TextProps>
) {
const Component = as || "p";
return (
<Component data-tone={tone} {...rest}>
{children}
</Component>
);
}
Esse padrão evita múltiplas versões de um mesmo componente.
Você não cria LinkText, BodyText, LabelText, CaptionText se o problema é semântico.
Você cria um contrato polimórfico.
O consumidor escolhe o elemento.
O núcleo continua pequeno.
O cuidado aqui é evidente.
Polimorfismo sem regras vira bagunça.
Se a API aceita combinações inválidas, OCP vira fumaça.
Por isso never, unions discriminadas e validação de tipos importam tanto.
No backend, OCP fica mais claro quando o caso de uso é separado do detalhe. O caso de uso não deveria conhecer gateway concreto. Não deveria saber se a fila é Kafka ou SQS. Não deveria saber se o storage é Postgres ou Dynamo. Ele deveria chamar um contrato.
export interface PaymentGateway {
authorize(input: { amount: number; orderId: string }): Promise<{ id: string }>;
}
export class ConfirmOrder {
constructor(private readonly gateway: PaymentGateway) {}
async execute(orderId: string, amount: number) {
return this.gateway.authorize({ orderId, amount });
}
}
Esse tipo de desenho reduz impacto de mudança. Quando o gateway muda, o caso de uso não muda. Quando a API externa muda, o núcleo não muda. Quando a implementação falha, você troca o adapter.
OCP no backend protege sua velocidade. Ele evita que cada integração nova contamine a camada de negócio. Ele também facilita testes. O teste passa a mirar o contrato, não o detalhe.
Registries são úteis quando a variação não é conhecida toda de uma vez. Você tem regras de precificação. Você tem validadores. Você tem exportadores. Você tem providers. Cada nova regra entra como registro. O motor continua igual.
type RuleContext = {
country: string;
total: number;
customerType: "new" | "returning";
};
interface PricingRule {
id: string;
matches(ctx: RuleContext): boolean;
apply(ctx: RuleContext): RuleContext;
}
export class PricingEngine {
constructor(private readonly rules: PricingRule[]) {}
calculate(ctx: RuleContext) {
return this.rules
.filter((rule) => rule.matches(ctx))
.reduce((current, rule) => rule.apply(current), ctx);
}
}
Esse modelo funciona porque a extensão é declarativa. Você registra uma nova regra. Você não mexe no motor. O núcleo fica estável. As variações ficam acopladas ao contrato.
Quando isso é bem feito, o resultado parece simples. Mas a simplicidade veio da disciplina. Não da ausência de complexidade.
Design system é um campo de batalha clássico para OCP. Se cada nova demanda virar prop, o sistema degrada rápido. Se cada nova variante virar edição no núcleo, o sistema perde consistência. Se cada equipe puder abrir a primitive central, o design system deixa de ser sistema.
O melhor antídoto é definir uma base pequena. Depois, deixar a extensão acontecer em cima. Isso inclui wrappers, slots, variantes compostas e tokens.
O núcleo precisa dizer não com clareza. Ele precisa aceitar o suficiente. Ele não precisa aceitar tudo. Essa é uma diferença importante. Fechado não significa rígido. Fechado significa protegido por um contrato bom.
Se a extensão está certa no papel, mas quebra no uso, o contrato não está bom. Por isso observabilidade também é OCP. Você precisa saber quando uma extensão começou a gerar ruído. Você precisa saber quando uma variação passou a dominar o código. Você precisa saber quando uma nova opção virou risco.
Alguns sinais práticos ajudam muito. Taxa de uso por variante. Quantidade de mudanças no núcleo. Falhas por combinação de props. Tempo para criar uma variação nova. Tempo médio de review para um componente base.
Se esses números sobem, a arquitetura está gritando. OCP não foi quebrado de uma vez. Ele foi sendo corroído.
OCP não é gratuito. Cada ponto de extensão precisa ser pensado. Cada contrato precisa ser mantido. Cada abstração precisa valer o custo.
Se você exagera, cria complexidade desnecessária. Se você subestima a variação, cria acoplamento. O equilíbrio está em conhecer o problema real. Se a variação é estável, componha. Se a variação é rara, talvez um branch simples resolva. Se a variação está crescendo, abstraia antes de virar dívida.
O ponto mais importante é este. OCP não substitui julgamento. Ele organiza o julgamento.
Button com 20 props booleanas.variant infinito com nomes de campanha.if interno para cada cliente.switch com comportamento de produto inteiro.NotImplemented.any usado para driblar contrato.Esses anti-patterns contam a mesma história. O sistema não tem ponto de extensão. Ele tem improviso. Improvise pouco. Contrate muito. Ou melhor ainda, componha.
O arquivo responde a mais de um motivo de mudança?
A variação está escondida em if ou switch?
Existe um contrato explícito para a extensão?
A API mistura estrutura, semântica e política?
O componente raiz fica maior a cada ajuste?
Uma nova variação exige tocar no núcleo?
O teste do núcleo muda quando a extensão muda?
A extensão pode viver em outro arquivo?
O código aceita combinações inválidas?
O nome da abstração diz o que ela promete?
A mudança atual está adicionando comportamento ou revelando um contrato ausente?
A API consegue dizer não a combinações ruins?
O consumidor consegue estender sem editar o original?
A abstração reduz complexidade ou só a esconde?
O padrão escolhido combina com a forma da variação?
O núcleo depende de detalhe concreto?
A diferença entre casos está em estrutura, renderização ou regra?
Existe uma estratégia, slot ou adapter para esse caso?
O time consegue explicar o contrato em uma frase?
A alteração é uma extensão real ou um remendo?
Identifique a razão de mudança dominante.
Separe regra, estrutura e detalhe.
Extraia o contrato mínimo.
Mova a variação para composição.
Crie testes para o contrato.
Traga observabilidade para a extensão.
Remova if desnecessário do núcleo.
Reduza props booleanas.
Documente o ponto de extensão.
Congele o núcleo com mais confiança.
Meça o impacto da mudança.
Veja quantos arquivos ainda precisam abrir o núcleo.
Se crescerem em cadeia, repense o contrato.
Se o contrato ficou artificial, simplifique.
Se a abstração começou a doer, ela está cedo demais.
Se a variação já existe em três lugares, abstraia agora.
Se o núcleo continua mudando por um detalhe, extraia o detalhe.
Se o teste está frágil, revise a fronteira.
Se o time discorda do nome, o contrato está ruim.
Se o contrato ficou claro, o resto flui.
Um time de e-commerce tinha um ProductCard com muitas variações.
Badge de promoção.
Badge de estoque.
Modo compact.
Modo highlight.
CTA em posição variável.
Cada novo pedido reabria o mesmo arquivo.
O crescimento foi rápido.
A manutenção, lenta.
A refatoração começou por uma pergunta simples. O que realmente muda? Resposta: conteúdo, ações e destaque. Então o card virou composição. O núcleo virou pequeno. Os detalhes passaram a entrar por slots. O layout ficou previsível. As novas campanhas deixaram de exigir edição do mesmo componente.
Depois da mudança, o time mediu três coisas. Tempo para criar nova variação. Quantidade de regressões visuais. Quantidade de edições no núcleo. O resultado foi claro. Menos mudanças no coração. Mais extensões externas. Mais confiança nas entregas.
OCP significa nunca mudar o código? Não. Significa mudar o mínimo necessário e empurrar a variação para contratos melhores.
Herança é obrigatória para aplicar OCP? Não. Na maioria dos casos, composição é mais segura.
Todo componente precisa ser extensível? Não. Só os pontos que realmente recebem variação frequente.
OCP é só para UI? Não. Funciona em backend, integrações, filas, regras e qualquer módulo com contratos estáveis.
Como saber se abstraí cedo demais? Se a extensão ainda não apareceu e o contrato começou a parecer inventado, abstraiu cedo demais.
Como saber se abstraí tarde demais? Se a mesma mudança já abriu três arquivos e quatro testes, abstraiu tarde demais.
Posso usar switch sem violar OCP?
Pode, desde que o switch esteja em uma fronteira apropriada e não vire o centro da aplicação.
OCP compete com simplicidade? Não. Simplicidade é parte do objetivo.
OCP compete com performance? Normalmente não. Mas abstração mal desenhada pode atrapalhar.
Qual é a melhor pergunta de review? Esta mudança está abrindo o núcleo ou adicionando um ponto de extensão?
OCP é um princípio de higiene estrutural. Ele protege o código de mudanças triviais que poderiam acontecer fora do núcleo. Ele não impede evolução. Ele organiza a evolução.
Se você consegue adicionar comportamento sem reabrir o arquivo original, você ganhou. Se você precisa reabrir toda vez, o princípio ainda não está aplicado. Não porque você falhou. Mas porque a extensão ainda não foi desenhada como contrato.
O melhor sinal de que OCP está funcionando é silencioso. O núcleo fica estável. As variações entram por fora. Os testes ficam mais confiáveis. O time para de ter medo de mexer.
The file does not break all at once.
It gets reopened.
Every new exception asks for one more if.
Every new variant asks for one more prop.
Every new edge case asks for one more special branch.
At first, that feels productive.
Later, it becomes expensive change tax.
This is what OCP tries to stop. It does not try to stop change. It tries to stop repeated edits to the same core module for predictable variation. When the extension point is explicit, the code stays calm. When it is not, the code grows by infiltration.
The practical question is simple. Can the next variation enter from the outside? If yes, the design is healthy. If no, the core is still too open.
The classic definition is well known. Entities should be open for extension and closed for modification. In practice, that means something concrete. You define the stable behavior. You isolate the moving parts. You route change through explicit contracts.
OCP is not about line count. It is not about classes. It is not about framework choice. It is about the shape of change.
The core module must remain trustworthy. Behavior should not be rewritten for every new variation. Variations should arrive as strategies, slots, adapters, renderers, or plugins. That is the actual center of the principle.
In frontend code, the core may be a component. In backend code, the core may be a use case. In a design system, the core may be a primitive. In every case, the question is the same. How do I add behavior without breaking the existing behavior?
OCP does not mean "never edit existing code." If the contract is wrong, edit it. If the domain has changed, edit it. If you learned something real, refactor. What OCP fights is unnecessary reopening of the core for trivial variation.
OCP also does not mean "create abstractions as early as possible." Premature abstraction is another form of debt. If you invent extension points without real variation, you complicate the simple. If you create interfaces without a real use case, you create ceremony.
OCP is not the same as inheritance. Inheritance can violate it quickly. If the subtype needs extra preconditions or ignores base behavior, the contract is lying. That is not substitutability. That is a trap.
You do not need a heavy framework to apply OCP. You need clear seams. You need good naming. You need modules small enough to change safely.
If the file grows whenever a new rule appears, something is wrong.
If the same component owns UI, rules, and data access, something is wrong.
If every request adds another if instead of another contract, something is wrong.
If the variation is expressed through boolean props, something is wrong.
If tests fail for irrelevant details, something is wrong.
Other signs are louder.
The git blame is noisy.
Snapshots become landmines.
The component needs ten props to do the basics.
The docs become larger than the code.
The extension cost is higher than the feature itself.
When that happens, the issue is not just technical. It is cognitive. The team loses the map. People build different mental models of the same module. Without a contract, every extension becomes a guess.
The most useful patterns are not magic. They simply push variation away from the core. The most reliable ones are these.
as.Each one fits a different kind of variation.
Slots handle visual composition.
Render props handle rendering policy.
as handles semantic variation.
Strategies handle behavior alternatives.
Registries handle dynamic extension.
The common idea is simple. You do not edit the heart for every new case. You create a seam.
Slots work well when the problem is structural. Instead of a component receiving dozens of flags, it receives parts. Each part has a role. The core assembles the composition. The consumer chooses the layout.
import { createContext, ReactNode, useContext } from "react";
const PanelContext = createContext(false);
export function Panel({ children }: { children: ReactNode }) {
return (
<section className="panel">
<PanelContext.Provider value={true}>{children}</PanelContext.Provider>
</section>
);
}
Panel.Header = function PanelHeader({ children }: { children: ReactNode }) {
const inside = useContext(PanelContext);
if (!inside) throw new Error("Panel.Header must be used inside Panel");
return <header className="panel-header">{children}</header>;
};
Panel.Body = function PanelBody({ children }: { children: ReactNode }) {
return <div className="panel-body">{children}</div>;
};
Panel.Footer = function PanelFooter({ children }: { children: ReactNode }) {
return <footer className="panel-footer">{children}</footer>;
};
The benefit is immediate.
If you need a new badge, add a new slot.
If you need a new action area, add another slot.
The root component does not grow new if branches.
The contract stays stable.
This matters because design systems tend to rot through prop explosion. Composition grows by parts, not by flags. That keeps the API predictable. And predictable APIs are what OCP is buying you.
Render props work when the variation is policy, not structure. The component fetches data. The consumer decides how to render it. The core exposes state. The usage chooses the shape.
type QueryState<T> = {
data: T | null;
loading: boolean;
error: string | null;
};
type DataViewProps<T> = {
state: QueryState<T>;
children: (state: QueryState<T>) => React.ReactNode;
};
export function DataView<T>({ state, children }: DataViewProps<T>) {
return <>{children(state)}</>;
}
This is a strong choice when the logic is stable. You do not want to edit a data component every time the screen changes. You want to change the view. The screen becomes the extension. The core stays closed.
Headless components work in the same direction. They expose state and actions. They do not impose UI. That fits menus, tables, filters, comboboxes, and form flows very well.
asas prop polymorphism solves a very specific pain.
The visual behavior is the same.
The semantics change.
Sometimes the element must be a button.
Sometimes it must be an a.
Sometimes it must be a label.
type PolymorphicProps<C extends React.ElementType, P> = P &
{ as?: C } &
Omit<React.ComponentPropsWithoutRef<C>, keyof P>;
type TextProps = {
tone: "default" | "muted" | "strong";
};
export function Text<C extends React.ElementType = "p">(
{ as, tone, children, ...rest }: PolymorphicProps<C, TextProps>
) {
const Component = as || "p";
return (
<Component data-tone={tone} {...rest}>
{children}
</Component>
);
}
This avoids multiple copies of the same component.
You do not create LinkText, BodyText, CaptionText, and LabelText if the issue is semantics.
You create a polymorphic contract.
The consumer picks the element.
The core remains small.
The warning is obvious.
Polymorphism without rules becomes chaos.
If the API accepts invalid combinations, OCP is an illusion.
That is why never, discriminated unions, and type-level validation matter.
Backend OCP is clearest when the use case is separate from the detail. The use case should not know the concrete gateway. It should not know whether the queue is Kafka or SQS. It should not know whether storage is Postgres or Dynamo. It should talk to a contract.
export interface PaymentGateway {
authorize(input: { amount: number; orderId: string }): Promise<{ id: string }>;
}
export class ConfirmOrder {
constructor(private readonly gateway: PaymentGateway) {}
async execute(orderId: string, amount: number) {
return this.gateway.authorize({ orderId, amount });
}
}
This design reduces change impact. When the gateway changes, the use case does not. When the external API changes, the core does not. When an implementation fails, you replace the adapter.
That is OCP protecting velocity. It prevents every integration from polluting business logic. It also makes tests easier. The tests aim at the contract, not the vendor.
Registries help when the variation is not fully known upfront. You have pricing rules. You have validators. You have exporters. You have providers. Every new rule comes in as a registration. The engine stays the same.
type RuleContext = {
country: string;
total: number;
customerType: "new" | "returning";
};
interface PricingRule {
id: string;
matches(ctx: RuleContext): boolean;
apply(ctx: RuleContext): RuleContext;
}
export class PricingEngine {
constructor(private readonly rules: PricingRule[]) {}
calculate(ctx: RuleContext) {
return this.rules
.filter((rule) => rule.matches(ctx))
.reduce((current, rule) => rule.apply(current), ctx);
}
}
This works because the extension is declarative. You register a new rule. You do not edit the engine. The core stays stable. The variation stays behind a contract.
When done well, it looks simple. The simplicity is earned. It is not accidental.
Design systems are a classic OCP battleground. If every request becomes a new prop, the system decays quickly. If every variant reopens the core, consistency dies. If every team can edit the primitive, the system stops being a system.
The best antidote is a small base. Then let extension happen on top of it. That includes wrappers, slots, tokens, and composition helpers.
The core must be able to say no. It must accept enough. It does not need to accept everything. That distinction matters. Closed does not mean rigid. Closed means protected by a good contract.
If the extension looks right on paper but fails in use, the contract is weak. That is why observability is part of OCP. You need to know when an extension starts producing noise. You need to know when a variant is taking over the codebase. You need to know when a new option is becoming risky.
Useful signals help a lot. Variant usage rate. Number of core edits. Failures by prop combination. Time to create a new variation. Review time for the base component.
If those numbers rise, architecture is telling you something. OCP was not broken in a single event. It was slowly eroded.
OCP is not free. Every extension point has a cost. Every contract must be maintained. Every abstraction has to earn its place.
If you overdo it, you create unnecessary complexity. If you underdo it, you create coupling. The balance comes from understanding real variation. If variation is stable, compose. If variation is rare, maybe a simple branch is enough. If variation is growing, abstract before it turns into debt.
The most important point is this. OCP does not replace judgment. It organizes judgment.
Button with 20 boolean props.variant prop with campaign names.if branches per client.switch that becomes product logic.NotImplemented.any used to bypass the contract.These anti-patterns tell the same story. The system does not have a seam. It has improvisation. Improvise less. Contract more. Or better, compose.
Does this file have more than one reason to change?
Is variation hidden in if or switch branches?
Is there an explicit contract for extension?
Does the API mix structure, semantics, and policy?
Does the root component grow with every request?
Does every new variation require editing the core?
Does the core test change when the extension changes?
Can the extension live in another file?
Does the code allow invalid combinations?
Does the abstraction name match the promise?
Is the current change adding behavior or revealing a missing contract?
Can the API say no to bad combinations?
Can the consumer extend without touching the original?
Does the abstraction reduce complexity or just hide it?
Does the pattern match the shape of the variation?
Does the core depend on concrete detail?
Is the difference structure, rendering, or rule?
Is there a strategy, slot, or adapter for this case?
Can the team explain the contract in one sentence?
Is this a real extension or a patch?
Identify the dominant reason for change.
Separate rule, structure, and detail.
Extract the minimum contract.
Move variation into composition.
Write tests for the contract.
Add observability to the extension.
Remove unnecessary if branches from the core.
Reduce boolean props.
Document the extension point.
Keep the core smaller and calmer.
Measure the impact.
Count how many files still need the core.
If that count grows, revisit the contract.
If the contract feels fake, simplify it.
If the abstraction hurts, it is probably too early.
If the variation already exists in three places, abstract now.
If the core still changes for detail, extract the detail.
If the tests are brittle, review the seam.
If the team disagrees on the name, the contract is unclear.
If the contract is clear, the rest becomes easier.
An ecommerce team had a ProductCard with too many variants.
Promotion badge.
Stock badge.
Compact mode.
Highlight mode.
CTA in different positions.
Every new request reopened the same file.
The growth was fast.
The maintenance was slow.
The refactor began with a simple question. What actually changes? The answer was content, action, and emphasis. So the card became composition. The core got small. Details started entering through slots. The layout became predictable. Campaigns stopped requiring edits to the same component.
After the change, the team measured three things. Time to create a new variant. Number of visual regressions. Number of edits in the core. The result was clear. Less change in the heart. More extension on the outside. More confidence in delivery.
Does OCP mean never changing code? No. It means changing the minimum necessary and pushing variation into better contracts.
Is inheritance required to apply OCP? No. Composition is often safer.
Should every component be extensible? No. Only the ones with real, frequent variation.
Is OCP only for UI? No. It works in backend code, integrations, queues, rules, and any stable contract boundary.
How do I know I abstracted too early? If the extension has not appeared and the contract feels invented, it was too early.
How do I know I abstracted too late? If the same change already opened three files and four tests, it was too late.
Can I use switch without violating OCP?
Yes, if the switch lives at the right boundary and does not become the center of the app.
Does OCP compete with simplicity? No. Simplicity is part of the goal.
Does OCP compete with performance? Usually not. But a bad abstraction can get in the way.
What is the best review question? Does this change reopen the core or add a real extension point?
OCP is structural hygiene. It protects code from trivial change that should happen outside the core. It does not stop evolution. It organizes evolution.
If you can add behavior without reopening the original file, you won. If you need to reopen it every time, the principle is not fully in place. That does not mean you failed. It means the extension has not yet been designed as a contract.
The best sign that OCP is working is quiet. The core stays stable. The variations arrive from outside. Tests get more trustworthy. The team stops fearing edits.
if sempre que o time muda de ideia.git blame aponta para quase todo mundo.if por composição.switch central por estratégia.as.if do núcleo.OCP serve para micro detalhes? Não. Serve para mudanças que realmente aparecem com frequência.
OCP é só um nome bonito para composição? Composição é uma das melhores ferramentas para OCP, mas o princípio é mais amplo.
Posso quebrar OCP e ainda ter código bom? Sim, em casos simples. Mas o custo cresce rápido quando a mudança se repete.
Devo abstrair tudo? Não. Abstraia o suficiente para proteger o núcleo.
Quando parar de abstrair? Quando o contrato cumpre o trabalho e a complexidade extra deixa de se pagar.
if every time the team changes its mind.git blame points to almost everyone.if with composition.switch with a strategy.as.if from the core.Is OCP for micro details? No. It is for changes that appear often enough to matter.
Is OCP just a fancy name for composition? Composition is one of the best tools for OCP, but the principle is broader.
Can I break OCP and still have good code? Yes, in simple cases. But the cost grows fast once the change repeats.
Should I abstract everything? No. Abstract just enough to protect the core.
When should I stop abstracting? When the contract does the job and the extra complexity stops paying back.
Título: OCP: estenda sem reabrir o arquivo original
Resumo: O Open/Closed Principle não pede código imutável. Ele pede pontos de extensão claros. Quando você usa slots, strategies, registries e contratos de teste, novas variações entram sem reabrir o núcleo. Isso reduz regressões, melhora a previsibilidade e deixa o time mais rápido.
CTA: Se toda nova regra ainda abre o mesmo arquivo, OCP ainda não está aplicado.
Title: OCP: extend without reopening the original file
Summary: Open/Closed Principle does not demand frozen code. It demands clear extension seams. When you use slots, strategies, registries, and contract tests, new variations enter without reopening the core. That reduces regressions, improves predictability, and keeps the team moving faster.
CTA: If every new rule still opens the same file, OCP is not in place yet.