">
 

Chain of Responsibility Design Pattern: Decoupling Complex Business Rules, One Handler at a Time

Iniciado por joomlamz, Hoje at 02:15

Respostas: 1   |   Visualizações: 1

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Saudações, comunidade do **webmastersmz.com**!

Como especialista em tecnologia, analisei recentemente um tópico em inglês muito pertinente para quem está a dar os primeiros passos ou a aprimorar as suas competências em bases de dados: **"Where to Get a Sample Database to Practice SQL (And How to Check It Loaded)"** (Onde obter uma base de dados de exemplo para praticar SQL e como verificar se foi carregada com sucesso).

Aqui estão os pontos principais abordados no tópico, destrinchados com uma perspectiva técnica:

1. **A Importância de Dados Reais para Testes:**
   Praticar SQL apenas com tabelas vazias criadas por nós limita a capacidade de entender a complexidade de consultas (*queries*) avançadas. O tópico destaca a necessidade de usar bases de dados de exemplo padronizadas (como a clássica *Sakila*, *Northwind* ou *Chinook*), que simulam cenários reais de negócio com relacionamentos complexos entre chaves primárias e estrangeiras.

2. **Onde Encontrar Dados Confiáveis:**
   O artigo aponta repositórios oficiais e plataformas como o GitHub, o site oficial do MySQL/PostgreSQL e fontes comunitárias onde é possível descarregar ficheiros `.sql` ou `.bak` seguros, livres de *malware* e estruturados optimamente para motores de bases de dados relacionais.

3. **Verificação do Carregamento (*Validation*):**
   Um ponto técnico crítico mencionado é a validação pós-importação. Não basta apenas executar o script de importação e assumir que tudo correu bem. O autor recomenda o uso de comandos básicos de introspecção (como `SHOW TABLES;`, `SELECT COUNT(*);` em tabelas-chave, ou a verificação de restrições de integridade referencial) para garantir que o esquema e os dados foram integrados sem corrupção ou perda de pacotes.

**Vamos abrir o debate no fórum!**
Quais são as vossas preferências por aqui? Costumam utilizar as bases de dados clássicas como a *Northwind* para treinar índices e procedimentos armazenados, ou preferem gerar dados sintéticos com ferramentas automatizadas? Quais os maiores desafios que já enfrentaram ao importar grandes volumes de dados SQL para os vossos servidores de teste? Deixem as vossas experiências e dicas nos comentários abaixo!

---

Para garantir que os vossos projetos, aplicações e fóruns rodam sem falhas, com a máxima velocidade e estabilidade, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com.


                     Chain of Responsibility Design Pattern: Decoupling Complex Business Rules, One Handler at a Time
               




Tópico:
                     Chain of Responsibility Design Pattern: Decoupling Complex Business Rules, One Handler at a Time
               
Categoria: Tutoriais | FreeCodeCamp Premium
Idioma Principal: Português (Conteúdo de Tecnologia)

Conteúdo do Tutorial / Guia Passo a Passo:
-------------------------------------------------------------------------
Every system, at some point, ends up with a function that nobody wants to touch.

It starts small: a simple validation check, an if statement here, another there. Then requirements grow and more conditions get added. The function gets longer. Someone adds a comment that says "don't modify without reading the full thing first." The function becomes a rite of passage. New developers are warned about it during onboarding.

This is what happens when complex business rules pile up in one place without a deliberate structure to contain them.

The Chain of Responsibility pattern exists to prevent exactly this. Instead of one method that knows everything and does everything, you build a chain of focused handlers. Each handler knows one rule and checks whether the request passes its rule. If it does, the request moves forward to the next handler. If it doesn't, the chain stops right there.

No handler knows how long the chain is. No handler knows what comes before or after it. Each one just does its job and decides: stop here, or pass it forward.

Table of Contents

• What is the Chain of Responsibility Pattern?

• The Problem It Solves

• Core Components

• Real World Example One: Transaction Approval Flow

• Real World Example Two: User Onboarding Validation

• What Makes These Two Examples Interesting Together

• When to Use the Chain of Responsibility Pattern

• When Not to Use It

• Conclusion

What is the Chain of Responsibility Pattern?

The Chain of Responsibility is a behavioral design pattern that lets you pass a request along a chain of handlers. Each handler in the chain decides either to process the request and stop the chain, or to pass the request to the next handler.

The pattern gives you three things that matter in production systems.

First, it decouples the sender of a request from its receivers. The code that initiates a transaction validation doesn't know which handler will ultimately process it or stop it. It just starts the chain.

Second, it gives you a single responsibility per handler. Each handler owns exactly one business rule. When that rule changes, you modify one class. Nothing else changes.

Third, it makes the chain configurable. You can add, remove, or reorder handlers without touching existing handler code. A new compliance requirement becomes a new handler plugged into the chain, not a new branch inside an existing method.

The Problem It Solves

Here's what transaction validation looks like without the pattern:

void handleTransaction(Transaction transaction) {
if (transaction.isFraud) {
// block transaction
return;
}

if (!transaction.isKycVerified) {
// reject transaction
return;
}

if (!transaction.isAccountActive) {
// reject transaction
return;
}

if (transaction.amount < 50000) {
// junior officer approval
return;
}

if (transaction.amount <= 200000) {
// mid level approval
return;
}

if (transaction.amount <= 1000000) {
// manager approval
return;
}

// executive approval
}

This works today. Tomorrow your compliance team adds a credit score check. Your fraud team adds a velocity check. Your legal team adds a sanctions screening step. Your product manager adds a daily limit check.

Every new rule goes into this same method. The method grows to fifty lines. Then a hundred. The conditions interact in ways that are hard to reason about. Testing it requires setting up every possible combination of flags. A bu

... [O tutorial continua no link abaixo] ...


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: