pattern/enterprise/specification
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
Fluxo5 passos — reproduza para seguir o fluxo
- chamada
- resposta ou assíncrono
- falha
- passo
- toque num nó para focar
- Outras plantas de 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
and+1
or+1
- 1
Uma classe por regra com
isSatisfiedBy - 2
AbstractSpecificationimplementaandeoruma vez - 3
Produto =
renda.and(divida).or(garantia) - 4
Razão em pontos-base por multiplicação cruzadaLimite de 40% exato
Trade-offs
O que se ganha, o que se paga
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
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"}`);
Nível
introdutório
1/13
- Linhas de TypeScript
- 63
- Tipo
- A — código puro
Domínio financeiro
- Crédito/Empréstimo
- Antifraude
- Limite
Padrões do catálogo que implementa
- Specification
Trilhapasso 4 de 6
Lógica de domínio (PoEAA)
Por que se relacionam
Teste rápido
Qual destes combina com Specification?
Regras do domínio combináveis. Abrir Domain-Driven Design
Seu progresso
0/157 estudados
Fica salvo só neste navegador.