惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
SecWiki News
SecWiki News
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
小众软件
小众软件
C
CERT Recently Published Vulnerability Notes
Jina AI
Jina AI
N
Netflix TechBlog - Medium
GbyAI
GbyAI
IT之家
IT之家
Apple Machine Learning Research
Apple Machine Learning Research
AWS News Blog
AWS News Blog
G
GRAHAM CLULEY
L
Lohrmann on Cybersecurity
C
Cybersecurity and Infrastructure Security Agency CISA
I
Intezer
T
Tor Project blog
P
Palo Alto Networks Blog
P
Privacy & Cybersecurity Law Blog
P
Privacy International News Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Proofpoint News Feed
T
Tailwind CSS Blog
C
Check Point Blog
Cloudbric
Cloudbric
Y
Y Combinator Blog
The Last Watchdog
The Last Watchdog
Forbes - Security
Forbes - Security
Last Week in AI
Last Week in AI
S
Security Affairs
博客园 - Franky
F
Fortinet All Blogs
量子位
M
MIT News - Artificial intelligence
C
Cisco Blogs
酷 壳 – CoolShell
酷 壳 – CoolShell
Stack Overflow Blog
Stack Overflow Blog
S
Secure Thoughts
V
Visual Studio Blog
AI
AI
美团技术团队
B
Blog RSS Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 三生石上(FineUI控件)
阮一峰的网络日志
阮一峰的网络日志
Engineering at Meta
Engineering at Meta
人人都是产品经理
人人都是产品经理
Microsoft Security Blog
Microsoft Security Blog
T
Threatpost
Cyberwarzone
Cyberwarzone

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Decoupling with Chain of Responsibility Pattern in C#
Digital Craf · 2026-04-26 · via DEV Community

The article cooperates with the sample project. Walkthrough with the downloaded project is not required, but I recommend it for better understanding.

The sample project consists of two different approaches to validating the user's data within a registration. Two processors simulate the user's registration process.

BasicUserRegistrationProcessor.cs follows the simple path of if statements.

public class BasicUserRegistrationProcessor
{
  public void Register(User user)
  {
    if (string.IsNullOrWhiteSpace(user.Username))
    {
        throw new Exception("Username is required.");
    }
    if (string.IsNullOrWhiteSpace(user.Password))
    {
        throw new Exception("Password is required.");
    }
    if (user.BirthDate.Year > DateTime.Now.Year - 18)
    {
        throw new Exception("Age under 18 is not allowed.");
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

ChainPatternRegistrationProcessor.cs is taking advantage of the Chain of Responsibility Pattern. This implementation applies the same set of validations.

public class ChainPatternRegistrationProcessor
{
  public void Register(User user)
  {
    var handler = new UsernameRequiredValidationHandler();
    handler.SetNext(new PasswordRequiredValidationHandler())
        .SetNext(new OnlyAdultValidationHandler());
    handler.Handle(user);
  }
}

Enter fullscreen mode Exit fullscreen mode

Chain of Responsibility Pattern

Chain of Responsibility Pattern(ChoRP) is a pattern firstly presented in great book Design Patterns: Elements of Reusable Object-Oriented Software.

Illustration

We can achieve loose coupling in software design by practicing ChoRP. The pattern is a very powerful yet pretty simple to implement in our applications. It allows us to easily decouple parts of code to make it more readable, testable, extensible, and maintainable.

ChoRP comes from a family of the behavioral pattern, also like State Pattern.

How to manage states with State Design Pattern in C#?

Components of ChoRP

ChoRP consists of three components.

  1. Request
  2. Abstraction of Handler
  3. Concrete Handlers

One or more Concrete Handlers will take care of Request in the chained process. Mostly, the Request is some kind of contract or Data Transfer Object of the handling event. In the sample project, it is a User class.

public class User
{
  public string Username { get; set; }
  public string Password { get; set; }
  public DateTime BirthDate { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

I am usually using the interface and the abstract class together as the abstraction for the Concrete Handlers. It contains two methods; Handle and SetNext.

public abstract class Handler<T> : IHandler<T> where T : class
{
  private IHandler<T> Next { get; set; }
  public virtual void Handle(T request)
  {
      Next?.Handle(request);
  }
  public IHandler<T> SetNext(IHandler<T> next)
  {
      Next = next;
      return Next;
  }
}
public interface IHandler<T> where T : class
{
  IHandler<T> SetNext(IHandler<T> next);
  void Handle(T request);
}

Enter fullscreen mode Exit fullscreen mode

T is a generic type of class which represents the Request. Method SetNext() sets a private property Next , which is subsequently invoked in the virtual method Handle(T request) .

Concrete Handler inherits from the abstract class Handler and implements an interface IHandler.

public class OnlyAdultValidationHandler : Handler<User>, IHandler<User>
{
  public override void Handle(User user)
  {
    if (user.BirthDate.Year > DateTime.Now.Year - 18)
    {
        throw new Exception("Age under 18 is not allowed.");
    }
    base.Handle(user);
  }
}

Enter fullscreen mode Exit fullscreen mode

OnlyAdultValidationHandler class overrides Handle method of its parent but also invokes the parent's Handle the method at the end of the method's body. This is a crucial factor for chaining Concrete Handlers. Also, by inheriting from the Handler class, the OnlyAdultValidationHandler gains SetNext method threw which we will set another chain segment.

Chaining Handlers

First, you need to set up the chain via the SetNext method. The method returns IHandler type so you can set Handlers in a row.

SetNext(new Handler()).SetNext(new Handler())

Once we finish the chain definition, we can continue by invoking Handler.Handle(request) which will call base.Handle(user) therefore Next?.Handle(request) ensures that the chain reaction is triggered.

Illustration

Drawbacks of Coupled Implementations

Why so much workaround? The basic implementation looks much more straightforward and readable than ChoRP implementation, right?

Well, it is not clear at first look, but those validations are tightly coupled. Password Validation is dependent on the result of Username Validation. Only Adult Age Validation is dependent on the result of previous validations.

It is even more evident if you write unit tests that are going to test different scenarios of user registration. You are not able to test Password Validation without introducing value into the user's Username property.

public class BasicUserRegistrationTests
{
    [Fact]
    public void When_Username_Is_Empty_Then_Exception
    _Should_Be_Thrown()
    {
        //Arrange
        var user = new User();
        //Act
        Action act = () => new BasicUserRegistrationProcessor()
        .Register(user);
        //Assert
        act.Should().Throw<Exception>();
    }
    [Fact]
    public void When_Password_Is_Empty_Then_Exception
    _Should_Be_Thrown()
    {
        //Arrange
        var user = new User
        {
            Username = "Daniel Rusnok"
        };
        //Act
        Action act = () => new BasicUserRegistrationProcessor()
        .Register(user);
        //Assert
        act.Should().Throw<Exception>();
    }

Enter fullscreen mode Exit fullscreen mode

But once you apply a ChoRP, then you are not only able to test Password Validation result, but also you are able to test both possible results of Password Validation which are Throw<Exception> when the password property is empty and NotThrow<Exception> when the password property is filled.

public class ChainPatternRegistrationTests
{
    [Fact]
    public void When_Password_Is_Empty_Then_Exception
    _Should_Be_Thrown()
    {
        //Arrange
        var user = new User{Password = string.Empty};

        //Act
        Action act = () => new PasswordRequiredValidationHandler()
        .Handle(user);

        //Assert
        act.Should().Throw<Exception>();
    }

    [Fact]
    public void When_Password_Is_Filled_Then_Exception
    _Should_NOT_Be_Thrown()
    {
        //Arrange
        var user = new User{Password = Guid.NewGuid().ToString()};

        //Act
        Action act = () => new PasswordRequiredValidationHandler()
        .Handle(user);

        //Assert
        act.Should().NotThrow<Exception>();
    }

Enter fullscreen mode Exit fullscreen mode

With BasicUserRegistrationProcessor we are only able to test if Password Validation NotThrow<Exception> when the whole user object is valid. And this is the biggest demonstration of how basic registration implementation is coupled.

[Fact]
public void When_All_Properties_Are_valid_Then_Exception_Should_NOT_Be_Thrown()
{
    //Arrange
    var user = new User
    {
        Username = "Daniel Rusnok",
        Password = Guid.NewGuid().ToString(),
        BirthDate = DateTime.Now.AddYears(-20)
    };
    //Act
    Action act = () => new BasicUserRegistrationProcessor()
    .Register(user);
    //Assert
    act.Should().NotThrow<Exception>();
}

Enter fullscreen mode Exit fullscreen mode

Summary

The power of decoupling is not only in its independent testability but also in its reusability. Such a Handler does not always have to accept a concrete type as a parameter. It can take an abstraction of the specific type like an interface.

Multiple types of Requests can implement such an interface. In such situations, the Handler becomes useable for various processes, and you are not repeating yourself. So ChoRP also supports the DRY.

Related Reading


Subscribe to Digital Craft Workshop on Substack