Pular para o conteúdo

Specification

Cada regra é um objeto com isSatisfiedBy(candidato), combinável por and e or. Use quando regras de elegibilidade ou antifraude se recombinam por contexto.

passos
4
arquivos
4
testes
0
tecnologias
2

Cenário

Empréstimo aprovado por perfil sólido (renda mínima e dívida ≤ 40%) ou por garantia; o cliente tem renda baixa e oferece garantia.

Planta

Fluxo
5/5
Renda mínima R$ 3.000EDívida até 40% da rendaOUTem garantiaEmpréstimo pessoal
5

5 passos — reproduza para seguir o fluxo

Como funciona

4passos

Cada regra é um objeto com isSatisfiedBy(candidato), combinável por and e or

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    Uma classe por regra com isSatisfiedBy

  2. 2

    AbstractSpecification implementa and e or uma vez

  3. 3

    Produto = renda.and(divida).or(garantia)

  4. 4

    Razão em pontos-base por multiplicação cruzadaLimite de 40% exato

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Regra reusada entre produtos

  • Regra testável sozinha

Custos

  • Uma classe por regra

  • Não diz qual regra reprovou

Código

pattern/enterprise/specification

4 arquivos

./

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

src/

  • demo.tsdemo

Executar só Bun

  1. bun run demo# roda o cenário

Saída: APP-002, com renda de R$ 2.000,00 abaixo do mínimo, é aprovado pela garantia (APPROVED).

Requisitos
Bun

Código

src/demo.ts

// Demo: credit rules as specification objects, combined with and/or into the personal loan eligibility.
type CreditApplicant = { applicantId: string; incomeMonthlyCents: number; debtMonthlyCents: number; collateralHas: boolean };

// and/or are written once here and inherited by every concrete rule; the composites are specifications too.
abstract class AbstractSpecification<T> {
  abstract isSatisfiedBy(candidate: T): boolean;

  and(other: AbstractSpecification<T>): AbstractSpecification<T> {
    return new SpecificationAnd(this, other);
  }

  or(other: AbstractSpecification<T>): AbstractSpecification<T> {
    return new SpecificationOr(this, other);
  }
}

class SpecificationAnd<T> extends AbstractSpecification<T> {
  constructor(
    private readonly left: AbstractSpecification<T>,
    private readonly right: AbstractSpecification<T>,
  ) {
    super();
  }

  isSatisfiedBy(candidate: T): boolean {
    return this.left.isSatisfiedBy(candidate) && this.right.isSatisfiedBy(candidate);
  }
}

class SpecificationOr<T> extends AbstractSpecification<T> {
  constructor(
    private readonly left: AbstractSpecification<T>,
    private readonly right: AbstractSpecification<T>,
  ) {
    super();
  }

  isSatisfiedBy(candidate: T): boolean {
    return this.left.isSatisfiedBy(candidate) || this.right.isSatisfiedBy(candidate);
  }
}

// One rule per class; none knows the others.
class SpecificationIncomeMin extends AbstractSpecification<CreditApplicant> {
  constructor(private readonly incomeMinCents: number) {
    super();
  }

  isSatisfiedBy(applicant: CreditApplicant): boolean {
    return applicant.incomeMonthlyCents >= this.incomeMinCents;
  }
}

// Ratio in basis points (4000 = 40%) compared by cross-multiplication: integers only, no rounding at the edge.
class SpecificationDebtToIncomeMax extends AbstractSpecification<CreditApplicant> {
  constructor(private readonly ratioMaxBasisPoints: number) {
    super();
  }

  isSatisfiedBy(applicant: CreditApplicant): boolean {
    return applicant.debtMonthlyCents * 10_000 <= applicant.incomeMonthlyCents * this.ratioMaxBasisPoints;
  }
}

class SpecificationCollateralHas extends AbstractSpecification<CreditApplicant> {
  isSatisfiedBy(applicant: CreditApplicant): boolean {
    return applicant.collateralHas;
  }
}

// Personal loan: a solid profile, or collateral in its place.
const LOAN_INCOME_MIN_CENTS = 300_000;
const LOAN_DEBT_TO_INCOME_MAX_BPS = 4_000;
const eligibilityLoan = new SpecificationIncomeMin(LOAN_INCOME_MIN_CENTS).and(new SpecificationDebtToIncomeMax(LOAN_DEBT_TO_INCOME_MAX_BPS)).or(new SpecificationCollateralHas());

const applicant: CreditApplicant = { applicantId: "APP-002", incomeMonthlyCents: 200_000, debtMonthlyCents: 50_000, collateralHas: true };
console.log(`  [CREDIT] ${applicant.applicantId} income R$ 2000.00, with collateral → ${eligibilityLoan.isSatisfiedBy(applicant) ? "APPROVED" : "REJECTED"}`);

Por que se relacionam

Teste rápido

Qual destes combina com Specification?

Próximo projeto, Padrões EnterpriseTransaction Script
Esc

↑ ↓ navegarEnter abrir239 resultados