Pular para o conteúdo

SOLID

Os cinco princípios de design orientado a objetos de Robert C. Martin, um arquivo por princípio. Use para manter classes pequenas, extensíveis e substituíveis sem reescrever o que já funciona.

passos
5
arquivos
9
testes
0
tecnologias
2

Cenário

Banco digital: extrato, antifraude de PIX noturno, carteira com conta corrente e CDB, gateways de cartão e PIX, notificação de transferência.

Planta

Fluxo
4/4
SRPcálculo do extratoseparado do layoutOCPregra antifraude novasem editar o motorLSPCDB não finge serconta com saqueISPPIX não implementaparcelamentoDIPtransferência depende dainterface do notificador
4

4 passos — reproduza para seguir o fluxo

Como funciona

5passos

Os cinco princípios de design orientado a objetos de Robert C. Martin, um arquivo por princípio

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    srp.ts: statementTotalsCalculate muda com a contabilidade; statementCsvFormat e statementTextFormat mudam com o layout

  2. 2

    ocp.ts: transferAnalyze não muda; a regra de PIX noturno entra como novo InterfaceRuleFraud

  3. 3

    lsp.ts: AccountBrokenCdb quebra quem usa AccountBroken; InterfaceAsset e InterfaceAccountWithdrawable corrigem

  4. 4

    isp.ts: GatewayPaymentPix implementa só cobrança e estorno; parcelamento fica em InterfacePaymentInstallment

  5. 5

    dip.ts: ServiceTransfer define InterfaceNotifierTransfer; texto e JSON a implementam

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Mudança de layout ou regra nova sem editar o resto

  • Gateway e notificador trocáveis sem tocar no negócio

Custos

  • Mais interfaces e arquivos para ler

  • Cedo demais vira interface de uma implementação só

Código

pattern/principles/solid

9 arquivos

./

  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo
  • dip.ts
  • isp.ts
  • lsp.ts
  • ocp.ts
  • srp.ts

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

Saída: os cinco princípios em ordem; o extrato fecha em R$ 7.940,10 nos dois layouts, a regra noturna recusa o PIX de R$ 1.500,00, o CDB quebra o saque herdado, o cartão parcela R$ 1.000,00 em 333,34 + 333,33 + 333,33 e os saldos terminam em R$ 2.600,00 e R$ 2.400,00.

Um princípio só: bun run srp, ocp, lsp, isp ou dip.

Requisitos
Bun

Código

src/demo.ts

// Demo: the five principles in order, one module each; importing a module runs its scenario.
import "./srp.ts";
import "./ocp.ts";
import "./lsp.ts";
import "./isp.ts";
import "./dip.ts";

src/dip.ts

// DIP: the transfer policy owns the notifier abstraction; the output channels depend on it, not the reverse.
type Account = { id: string; balanceCents: number };
type TransferReceipt = { from: string; to: string; amountCents: number };

// Declared by the high-level module, shaped by what the policy needs, not by any channel.
interface InterfaceNotifierTransfer {
  send(receipt: TransferReceipt): void;
}

class ServiceTransfer {
  constructor(private readonly notifier: InterfaceNotifierTransfer) {}

  transfer(from: Account, to: Account, amountCents: number): void {
    if (amountCents > from.balanceCents) throw new Error(`insufficient funds in ${from.id}`);
    from.balanceCents -= amountCents;
    to.balanceCents += amountCents;
    this.notifier.send({ from: from.id, to: to.id, amountCents });
  }
}

// Low-level details: each one implements the policy's interface.
class NotifierTransferText implements InterfaceNotifierTransfer {
  send(receipt: TransferReceipt): void {
    console.log(`[DIP] text: R$ ${(receipt.amountCents / 100).toFixed(2)} from ${receipt.from} to ${receipt.to}`);
  }
}

class NotifierTransferJson implements InterfaceNotifierTransfer {
  send(receipt: TransferReceipt): void {
    console.log(`[DIP] json: ${JSON.stringify({ event: "transfer.settled", ...receipt })}`);
  }
}

// Composition root: the only place that knows the concrete classes.
const alice: Account = { id: "acc-alice", balanceCents: 500_000 };
const bob: Account = { id: "acc-bob", balanceCents: 0 };
for (const notifier of [new NotifierTransferText(), new NotifierTransferJson()]) {
  new ServiceTransfer(notifier).transfer(alice, bob, 120_000);
}
console.log(`[DIP] balances: ${alice.id} R$ ${(alice.balanceCents / 100).toFixed(2)}, ${bob.id} R$ ${(bob.balanceCents / 100).toFixed(2)}`);

src/isp.ts

// ISP: small role interfaces, so PIX is not forced to implement card installments it does not have.
type Charge = { id: string; amountCents: number };

interface InterfacePaymentCharge {
  charge(amountCents: number): Charge;
}
interface InterfacePaymentRefund {
  refund(charge: Charge): string;
}
interface InterfacePaymentInstallment {
  installmentsPlan(amountCents: number, count: number): number[];
}

// Sequential charge ids keep the output identical on every run.
let chargeSequence = 0;
const chargeIdNext = (prefix: string) => `${prefix}-${String(++chargeSequence).padStart(4, "0")}`;

class GatewayPaymentCard implements InterfacePaymentCharge, InterfacePaymentRefund, InterfacePaymentInstallment {
  charge(amountCents: number): Charge {
    return { id: chargeIdNext("card"), amountCents };
  }

  refund(charge: Charge): string {
    return `card refund ${charge.id} queued to the acquirer`;
  }

  installmentsPlan(amountCents: number, count: number): number[] {
    const installmentCents = Math.floor(amountCents / count);
    return Array.from({ length: count }, (_, index) => (index === 0 ? amountCents - installmentCents * (count - 1) : installmentCents));
  }
}

// With one fat interface this class would need installmentsPlan() { throw }, which also breaks LSP.
class GatewayPaymentPix implements InterfacePaymentCharge, InterfacePaymentRefund {
  charge(amountCents: number): Charge {
    return { id: chargeIdNext("pix"), amountCents };
  }

  refund(charge: Charge): string {
    return `PIX return (devolução) ${charge.id} sent`;
  }
}

// Each client asks only for the role it uses.
function chargeRefund(gateway: InterfacePaymentCharge & InterfacePaymentRefund, amountCents: number): void {
  const charge = gateway.charge(amountCents);
  console.log(`[ISP] ${gateway.refund(charge)}`);
}

function checkoutInstallment(gateway: InterfacePaymentInstallment, amountCents: number, count: number): void {
  const plan = gateway.installmentsPlan(amountCents, count).map((cents) => (cents / 100).toFixed(2));
  console.log(`[ISP] R$ ${(amountCents / 100).toFixed(2)} in ${count}x → ${plan.join(" + ")}`);
}

chargeRefund(new GatewayPaymentCard(), 30_000);
chargeRefund(new GatewayPaymentPix(), 30_000);
checkoutInstallment(new GatewayPaymentCard(), 100_000, 3);

src/lsp.ts

// LSP: a subtype must honor the base contract; a CDB that refuses withdraw is not an account.
class AccountBroken {
  constructor(public balanceCents: number) {}

  withdraw(amountCents: number): void {
    if (amountCents > this.balanceCents) throw new Error("insufficient funds");
    this.balanceCents -= amountCents;
  }
}

// Violation: the override strengthens the precondition, so code written for AccountBroken breaks at runtime.
class AccountBrokenCdb extends AccountBroken {
  override withdraw(): void {
    throw new Error("locked until maturity");
  }
}

// Fix: only what can be withdrawn promises withdraw; the CDB promises a balance and nothing more.
interface InterfaceAsset {
  balanceCents: number;
}
interface InterfaceAccountWithdrawable extends InterfaceAsset {
  withdraw(amountCents: number): void;
}

class AccountChecking implements InterfaceAccountWithdrawable {
  constructor(public balanceCents: number) {}

  withdraw(amountCents: number): void {
    if (amountCents > this.balanceCents) throw new Error("insufficient funds");
    this.balanceCents -= amountCents;
  }
}

class InvestmentCdb implements InterfaceAsset {
  constructor(readonly balanceCents: number, readonly dateMaturity: string) {}
}

for (const account of [new AccountBroken(50_000), new AccountBrokenCdb(50_000)]) {
  try {
    account.withdraw(10_000);
    console.log(`[LSP] broken: ${account.constructor.name} withdrew R$ 100.00`);
  } catch (error) {
    console.log(`[LSP] broken: ${account.constructor.name} failed → ${(error as Error).message}`);
  }
}

// The compiler now rejects a CDB where a withdrawable account is expected; the runtime surprise is gone.
const checking = new AccountChecking(50_000);
const portfolio: InterfaceAsset[] = [checking, new InvestmentCdb(200_000, "2027-03-01")];
checking.withdraw(10_000);
const totalCents = portfolio.reduce((sum, asset) => sum + asset.balanceCents, 0);
console.log(`[LSP] fixed: checking withdrew R$ 100.00, portfolio total R$ ${(totalCents / 100).toFixed(2)}`);

src/ocp.ts

// OCP: the fraud engine is closed for modification; a new rule is a new entry, not an edit to the engine.
type Transfer = { amountCents: number; hour: number; isPayeeNew: boolean };

interface InterfaceRuleFraud {
  name: string;
  isViolated(transfer: Transfer): boolean;
}

const RULES_FRAUD: InterfaceRuleFraud[] = [
  { name: "amount above R$ 10000.00", isViolated: (transfer) => transfer.amountCents > 1_000_000 },
  { name: "new payee above R$ 2000.00", isViolated: (transfer) => transfer.isPayeeNew && transfer.amountCents > 200_000 },
];

// Closed: this function never changes when the bank adds a rule.
function transferAnalyze(transfer: Transfer, rules: InterfaceRuleFraud[]): string[] {
  return rules.filter((rule) => rule.isViolated(transfer)).map((rule) => rule.name);
}

// Open: the night PIX limit (20h to 6h) arrives as an extension, without editing the engine or the old rules.
const ruleFraudNight: InterfaceRuleFraud = {
  name: "night PIX above R$ 1000.00",
  isViolated: (transfer) => (transfer.hour >= 20 || transfer.hour < 6) && transfer.amountCents > 100_000,
};

const transfer: Transfer = { amountCents: 150_000, hour: 23, isPayeeNew: false };
const reportBefore = transferAnalyze(transfer, RULES_FRAUD);
const reportAfter = transferAnalyze(transfer, [...RULES_FRAUD, ruleFraudNight]);
console.log(`[OCP] PIX R$ 1500.00 at 23h, base rules  → ${reportBefore.length ? reportBefore.join(", ") : "approved"}`);
console.log(`[OCP] PIX R$ 1500.00 at 23h, + night rule → ${reportAfter.length ? reportAfter.join(", ") : "approved"}`);

src/srp.ts

// SRP: statement totals change with accounting rules, the layout changes with the product; one module each.
type Entry = { date: string; description: string; amountCents: number };
type StatementTotals = { creditsCents: number; debitsCents: number; balanceCents: number };

const centsFormat = (cents: number): string => (cents / 100).toFixed(2);

// Reason to change: accounting, which decides what counts as credit, debit and closing balance.
function statementTotalsCalculate(entries: Entry[], balanceOpeningCents: number): StatementTotals {
  const creditsCents = entries.filter((entry) => entry.amountCents > 0).reduce((sum, entry) => sum + entry.amountCents, 0);
  const debitsCents = entries.filter((entry) => entry.amountCents < 0).reduce((sum, entry) => sum - entry.amountCents, 0);
  return { creditsCents, debitsCents, balanceCents: balanceOpeningCents + creditsCents - debitsCents };
}

// Reason to change: the file the customer downloads; it formats totals and never recomputes them.
function statementCsvFormat(entries: Entry[], totals: StatementTotals): string {
  const rows = entries.map((entry) => `${entry.date};${entry.description};${centsFormat(entry.amountCents)}`);
  return [
    "date;description;amount",
    ...rows,
    `;credits;${centsFormat(totals.creditsCents)}`,
    `;debits;${centsFormat(totals.debitsCents)}`,
    `;balance;${centsFormat(totals.balanceCents)}`,
  ].join("\n");
}

// A second layout is a new formatter; the accounting module is not touched.
function statementTextFormat(totals: StatementTotals): string {
  return `credits R$ ${centsFormat(totals.creditsCents)} | debits R$ ${centsFormat(totals.debitsCents)} | balance R$ ${centsFormat(totals.balanceCents)}`;
}

const entries: Entry[] = [
  { date: "2026-10-01", description: "salary", amountCents: 850_000 },
  { date: "2026-10-03", description: "PIX sent", amountCents: -120_000 },
  { date: "2026-10-05", description: "boleto paid", amountCents: -35_990 },
];

const totals = statementTotalsCalculate(entries, 100_000);
console.log("[SRP] CSV layout");
console.log(statementCsvFormat(entries, totals));
console.log("[SRP] text layout, same totals");
console.log(statementTextFormat(totals));
Esc

↑ ↓ navegarEnter abrir239 resultados