Pular para o conteúdo
  1. Atlas
  2. GoF

Builder

Monta um objeto complexo por chamadas nomeadas em qualquer ordem e valida tudo de uma vez em build(), devolvendo todas as violações ou o objeto imutável.

passos
4
arquivos
4
testes
0
tecnologias
2

Cenário

Proposta de R$ 80.000,00 em 48 meses: acima de 24 meses exige garantia de 120% do valor; com garantia a taxa cai de 2,50% para 2,00% a.m.

Planta

Sequência
7/7
alt[alguma regra violada][tudo válido]withTerm(48)1withCollateral(vehicle, R$ 96.000,00)2withAmount(R$ 80.000,00)3build()4ErrorCreditProposalInvalid com todas as violações5taxa com desconto, Object.freeze6proposta imutável7Canal de créditoBuilderCreditProposalCreditProposal
7

7 passos — reproduza para seguir o fluxo

Como funciona

4passos

Monta um objeto complexo por chamadas nomeadas em qualquer ordem e valida tudo de uma vez em build(), devolvendo todas as violações ou o objeto imutável

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

build()+1
  1. 1

    withX() só grava e devolve o builder

  2. 2

    build() roda as regras cruzadas

  3. 3

    Violações juntas em ErrorCreditProposalInvalid.violations

  4. 4

    Resultado com Object.freeze, garantia inclusa

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Legível com muitos opcionais

  • Regras cruzadas num lugar só

Custos

  • Uma classe a mais por objeto

  • Erro só aparece no build()

Código

pattern/gof/builder

4 arquivos

./

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

src/

  • demo.tsdemo

Executar só Bun

  1. bun run demo# roda o cenário

Saída: a proposta sem valor e sem garantia é recusada com as duas violações juntas; a de R$ 80.000,00 em 48 meses com garantia sai congelada a 2,00% a.m.

Requisitos
Bun

Código

src/demo.ts

// Demo: a credit proposal assembled step by step in any order, validated once in build() and returned frozen.
type Collateral = { readonly type: "vehicle" | "real_estate"; readonly valueCents: number };
type CreditProposal = { readonly amountCents: number; readonly termMonths: number; readonly collateral: Collateral | null; readonly monthlyRateBps: number };

const TERM_MAX_WITHOUT_COLLATERAL = 24;
// The collateral must cover 120% of the amount: the margin absorbs the loss of value in a forced sale.
const COLLATERAL_COVERAGE_PERCENT = 120;
const RATE_BASE_BPS = 250;
const RATE_COLLATERAL_DISCOUNT_BPS = 50;

class ErrorCreditProposalInvalid extends Error {
  override name = "ErrorCreditProposalInvalid";
  constructor(readonly violations: string[]) {
    super(`invalid credit proposal: ${violations.join("; ")}`);
  }
}

// Each withX() only stores a value; every cross-field rule runs once, in build(), with all fields known.
class BuilderCreditProposal {
  private amountCents = 0;
  private termMonths = 0;
  private collateral: Collateral | null = null;

  withAmount(amountCents: number): this {
    this.amountCents = amountCents;
    return this;
  }

  withTerm(termMonths: number): this {
    this.termMonths = termMonths;
    return this;
  }

  withCollateral(type: Collateral["type"], valueCents: number): this {
    this.collateral = { type, valueCents };
    return this;
  }

  // Every violation at once: the customer fixes the whole form in one go.
  build(): CreditProposal {
    const violations = [
      ...(this.amountCents <= 0 ? ["amount is required"] : []),
      ...(this.termMonths > TERM_MAX_WITHOUT_COLLATERAL && !this.collateral ? [`term above ${TERM_MAX_WITHOUT_COLLATERAL} months requires collateral`] : []),
      ...(this.collateral && this.collateral.valueCents * 100 < this.amountCents * COLLATERAL_COVERAGE_PERCENT ? [`collateral must cover ${COLLATERAL_COVERAGE_PERCENT}% of the amount`] : []),
    ];
    if (violations.length > 0) throw new ErrorCreditProposalInvalid(violations);
    const monthlyRateBps = RATE_BASE_BPS - (this.collateral ? RATE_COLLATERAL_DISCOUNT_BPS : 0);
    return Object.freeze({ amountCents: this.amountCents, termMonths: this.termMonths, collateral: this.collateral && Object.freeze({ ...this.collateral }), monthlyRateBps });
  }
}

// Same term without collateral and no amount: build() reports both violations at once.
try {
  new BuilderCreditProposal().withTerm(48).build();
} catch (error) {
  if (!(error instanceof ErrorCreditProposalInvalid)) throw error;
  console.log(`  [REJECTED] ${error.violations.join("; ")}`);
}

const proposal = new BuilderCreditProposal().withTerm(48).withCollateral("vehicle", 9_600_000).withAmount(8_000_000).build();
console.log(`  [CREDIT] R$ ${(proposal.amountCents / 100).toFixed(2)} in ${proposal.termMonths} months, ${proposal.collateral?.type} collateral, ${(proposal.monthlyRateBps / 100).toFixed(2)}% a.m., frozen: ${Object.isFrozen(proposal)}`);

Por que se relacionam

Teste rápido

Qual destes combina com Builder?

Próximo projeto, GoFChain of Responsibility
Esc

↑ ↓ navegarEnter abrir239 resultados