design patterns – Chain of responsibility look alike but choose handler at runtime

Currently I have an structure of PopUps and I’ve been thinking to use Chain of Responsibility pattern, but the difference is a popup can back to previous one PopUp and also can go to any other PopUp.
I’ve been thinking to use chain of responsibility, but I think maybe is not the Ideal once chain of responsibility only goes forward.

Can you help me in this case? Which should be the best pattern? I thought something like a layer structure or something like.


PopUp can go to Any other PopUp N  to N

What is the responsibility of Infrastructure layer in a clean architecture?

I am trying to follow clean architecture by uncle bob. I have 3 layers

  • Core (Hosts business logic, and is the central layer)
  • Application (Host application usecases, and is directly above the core)
  • Infrastructure

I know the responsibility of infrastructure layer is to host any external dependencies that our application needs. But I have few questions about Infrastructure layer.

  1. Does Infrastructure layer is responsible to fulfill interfaces defined in Core only? Or it is supposed to fulfill the interfaces of any other layer that needs external dependency. For example, Application or UI etc.

  2. Infrastructure layer is always depicted as the last layer in onion architecture, then how come it can depend upon the core? Isn’t the layers are supposed to directly depend on the layers immediately below them?

  3. Let’s say I have an interface IExternalDep in the core and I created it’s implementation in the infrastructure layer. Now how can my other layers use this implementation? What is the way to provide the implementation during runtime without directly depending upon the infrastructure, as we know it is the outermost layer.

c# – Embedded services using chain of responsibility?

I currently have a few “worker services” that wrap existing code to automate incredibly repetitive code. A few examples are:

  • Method analytics.
  • Iteration support.
  • Exception logging.

My current setup requires me to wrap my code in layers:

AnalyticsService.Run((analyticsContext) => {
    IterationService.Run((iterationContext) => {
        ExceptionService.Run((exceptionContext) => {

I’m not a big fan of this, as I have hundreds of methods that need to use these interchangeably. So, after some searching, and posting a question with an XY problem on Stack Overflow, a commenter pointed me in the direction of the chain of responsibility pattern.

I love the pattern, and it looked like it would fit well at first glance, so I wrote up a simple implementation to test it out:

class Program
    static void Main(string() args)
        var testService = new AnalyticsService(new IterationService());
        testService.Process((context) =>
            Console.WriteLine("Comencing test.");
            for (int i = 0; i < 100; i++)
                if (i % 10 == 0)

internal interface IEmbeddableServiceContext
    void Exit();
internal sealed class EmbeddableServiceContext : IEmbeddableServiceContext
    public bool ShouldExit { get; private set; } = false;
    public void Exit() => ShouldExit = true;
internal abstract class EmbeddableService
    private EmbeddableService _embeddedService;
    public EmbeddableService() { }
    public EmbeddableService(EmbeddableService embeddedService) => _embeddedService = embeddedService;
    public void Process(Action<IEmbeddableServiceContext> request)
        if (request == null)

        var context = new EmbeddableServiceContext();
        Execute(context, (embeddedContext) =>
            if (_embeddedService != null)
    protected abstract void Execute(EmbeddableServiceContext context, Action<IEmbeddableServiceContext> request);
internal sealed class AnalyticsService : EmbeddableService
    public AnalyticsService() { }
    public AnalyticsService(EmbeddableService embeddedService) : base(embeddedService) { }

    protected override void Execute(EmbeddableServiceContext context, Action<IEmbeddableServiceContext> request)
        var startTime = DateTime.Now;
        Console.WriteLine($"Your request took {(DateTime.Now - startTime).TotalMilliseconds}ms to complete.");
internal sealed class IterationService : EmbeddableService
    public IterationService() { }
    public IterationService(EmbeddableService embeddedService) : base(embeddedService) { }
    protected override void Execute(EmbeddableServiceContext context, Action<IEmbeddableServiceContext> request)
        while (true)
            if (context.ShouldExit)

The biggest issue I have with this implementation is that the context models are now forced to be combined unless I want a maintenance nightmare. However, I wanted to get some feedback on the current implementation, before I take the next steps into further automating the developer implementation experience.

NOTE: Please don’t mind the fact that everything is marked as internal here. That’s a separate issue altogether.

single responsibility – Mixing an API server and a background worker

What are your thoughts on having a service/process be both an API server and a background worker, consuming messages off a queue like SQS?

I have typically kept these two separate to keep single responsibilities for each, but also it seems weird, at least in NodeJS, to have an API server bootstrap itself to be an API server but then also start polling a queue for jobs to be done.

Is it a fairly common practice to mix the two into the same service? If not other other strong reasons to keep them separate? Also somewhat tangential but would the same logic apply for an API server and a Kafka consumer?

c# – Other than the intent, is there a difference in how you implement Chain of Responsibility and Decorator Pattern?

I think it’s fair to say that they are quite similar to each other.
The only difference that I know is the intent.

Chain of Responsibility: Avoid coupling between the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. Not all objects may get chance or be able to handle the request.

Decorator : Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality. All decorator objects handle the request by enhancing the data in their own way.

But is there a difference if implementation? Apart from the fact that in Chain of responsibility you could break the chain at any point?

The following is an example of Decorator Pattern. But if you had asked me to write an example of Chain of responsibility, I could have written the same example.

Yes, I could have also added the condition where I check if the request is to be forwarded further and then break the chain, if not. But is that a mandatory thing for it to qualify as a Chain of Responsibility Pattern?

If it’s not then doesn’t the following serves as an example of both Chain of Responsibility and Decorator pattern? Does chain of responsibility differ only by an extra if condition that check if it is to be forwarded? Or is there more to it?

public interface IStream
    void write(string data);

public class CloudStream : IStream
    public void write(string data)
        Console.WriteLine("Writing to cloud storage..");

public class EncryptStream : IStream
    private IStream stream { get; set; }

    public EncryptStream(IStream stream)
    { = stream;

    public void write(string data)
        Console.WriteLine("Encrypting stream..");
        var encryptedData = Encrypt(data);;

    private object Encrypt(string data)
        return data; // return encrypted data

public class CompressStream : IStream
    private IStream stream { get; set; }

    public CompressStream(IStream stream)
    { = stream;

    public void write(string data)
        var compressedData = Compress(data);
        Console.WriteLine("Compressing stream..");;

    private object Compress(string data)
        return data;

design patterns – Should i overwrap functions to maintain Single Responsibility for code organisation?

So thanks to the link by Doc Brown, I am going to summarise what i have learnt:
I would like to use two factors to decide

  1. Scalability
  2. Dependency


If your codebase is something that is supposed to be maintained for a long period or if it is a throwaway program would decide if you should use a strict Single Responsibility way of organising. In the case of it having to be maintained, it is recommended to wrap all the functions to customise to your code’s objective and needs. This is because a third-party library is not customised to your needs all the way to the finest details. In the future, if you want to improve on the code, you can easily replace the libraries with better libraries or write your own optimised code. Also, it is easier for people to read as they do not need to look up those library APIs and simply need to refer to your code directly to understand what is going on.


If your code is highly dependent on those functionalities from the library you are using (in class C), you should always organise your code with each class performing a certain group of functionalities, even if it may seem to slow you down because it is easy to trace a problem when your code base gets too large. Also, it gets messy/untidy to read when a lot of those functionalities are incorporated. I would say this point can be subjective and when in doubt, just adopt a clear, organised way to think about the program, especially when coding with others.

single responsibility – Should a Car object be responsible for checking if it is able to run on certain Road objects?

I have 2 kinds of objects in my system, Car and Road.

A Car can be of various types and have properties like tire, tire size, engine, etc.

A Road can be of multiple types and have properties like terrain type, slippery, etc.

Some type of cars cannot ride on certain roads, based on the road properties and car limitations/constraints, like a common car cannot walk on beach sand because it would get stuck with smaller tires and weaker engine, but a “monster truck” could, because it has bigger tires and a better engine.

with that in mind, who should have the responsibility of checking whether a car can ride on a specific road?

i think that a Car should throw exceptions if it cannot ride, but i don’t think a Car should know in which road is going to ride.

  • should the road check the car’s properties and tell if it’s able to
    run on the road?
    i think this options falls to a procedural approach of getters/setters.

  • how would this scenario “scale” if a had multiple properties on a Car
    that could affect the capability of riding on a road?

how can i approach this?

base code:

export interface Car {
  engine: string;
  tire: string;
  tireSize: string;

  ride(): void // ride only if Road is compatible

export interface Road {
  terrain: string;
  isSlippery: boolean;
  cars: Car();

  startRace(): void

design – REST API noun vs verb and client vs server responsibility

I’m trying to delineate the responsibilities between client & server. I have the server parse a file, and then send back the uncategorized accounting transactions. The URL looks something like:

POST /api/accounts/:account_id/transaction_file // used for the upload
GET /api/accounts/:account_id/uncategorized // gets all the uncategorized accounts

Now, where it gets iffy is after I’ve categorized those accounts on the client-side, does it make more sense to send a POST back to:

POST /api/accounts/:account_id/uncategorized

Or should the client be responsible for DELETE-ing the uncategorized transactions and then POSTing a new transaction?

DELETE /api/accounts/:account_id/uncategorized/:uncategorized_id
POST /api/accounts/:account_id/transactions

This process seems to align much more with the answer found here.

However, it does feel “wrong” that the client should be the one owning this responsibility. Am I wrong to go about it this way?

php – Identifying Aggregate Root and Services Logic Responsibility

I’m attempting to refactor small meal planner following DDD, but I’m completely lost and overwhelmed in identifying the separation of concerns within my domain models.

Here’s the business requirement: A user can generate a 14 day plan consisting of 3 meals per day (collection of 42 Meal), they must provide their body info along with their meal plan preferences before they’re allowed to generate a plan. Their body info is only required to calculate the optimal caloric range per meal, whilst the meal preferences are mostly for sorting the recipes (provided from the subdomain).

I’ve came up with the following:

|-- App
|   `-- MealPlan
|       `-- Application
|       |   `-- Create
|       |   |   |-- CreateMealPlanService.php
|       |   `-- Find
|       `-- Domain
|       |   |-- Exception
|       |   |-- Services
|       |   |   |-- BuildMealsService.php
|       |   `-- Meal
|       |   |   |-- Meal.php
|       |   |   |-- MealId.php // uuid 
|       |   |   |-- Ingredients.php // VO
|       |   |   |-- Macros.php // vo
|       |   |   |-- Meals.php
|       |   `-- Profile
|       |   |   |-- Gender.php
|       |   |   |-- Height.php
|       |   |   |-- Unit.php
|       |   |   |-- Weight.php
|       |   |   |-- UserId.php // User Id from third party service sent through http requests
|       |   |   |-- Profile.php // ValueObject
|       |   `-- Preferences 
|       |   |   |-- Allergen.php
|       |   |   |-- Intolerance.php
|       |   |   |-- Preferences.php // ValueObject
|       |   |-- MealPlan.php // The aggregate root
|       |   |-- MealPlanId.php // uuid
|       |   |-- MealPlanRepositoryInterface.php
|       `-- Infrastructure
|           `-- Http
|           `-- Persistence
|               `--MealPlanRepository.php
`-- Recipes
|   `-- Application
|   `-- Domain
|   `-- Infrastructure
`-- Shared
    `-- Domain
    `-- Infrastructure

Use case: after authentication, during onboarding stage Profile and Preferences form data gets sent to CreateMealPlanService.

At this stage, I’m not sure if CreateMealPlanService should call BuildMealsService or if that logic should be within the MealPlan aggragate root, obviously a user MealPlan belongs to a user (tgethe UserId I put in the Profile as a VO, but I also think the MealPlan should have that UserId reference…).

I figured BuildMealsService would inject the RecipesService (from the Recipes Bounded Context), and there it’d generate the 42 meals, and passed to the MealPlan to be saved, but I’m not sure anymore at this point whose responsibility it really is.

Here’s the MealPlan aggragate root:

final class MealPlan {

    public function __construct(
        private MealPlanId $id,
        private Profile $profile,
        private Preferences $preferences,
        private Meals $meals

    public static function create(MealPlanId $id, Profile $profile, Preferences $preferences){
        return new self($id, $profile, $preferences);

    public function id(): MealPlanId {
        return $this->id;

    public function profile(): Profile {
        return $this->profile;

    public function preferences(): Preferences {
        return $this->preferences;

    public function meals(): Meals {
        return $this->meals;


python – Chain of Responsibility design

I’m trying to design a chain of responsibility pattern.

It slightly differ from traditional way when handler does only one action on a request, f.e. handles http response considering status code.

But my handlers have to do two actions. Below is an (dummy) example where handler asks a question first and then writes the user response to some store:

# some object where we keep surname and name 
class Request:

# some outer storage
store = {}

# chain of responsibility implementation

class PersonIdentifier:

    def __init__(self) -> None:
        self.handlers = ()

    def add_handler(self, handler):
        if self.handlers:

    def handle(self, request):
        return self.handlers(0).handle_request(request)

# handlers for chain of responsibility

class BaseHandler:
    handler_name = None

    def __init__(self) -> None:
        self.next_handler = None

    def set_next_handler(self, handler):
        self.next_handler = handler

class SurnameHandler(BaseHandler):
    handler_name = 'surname'
    handler_name_answer = 'surname-answer'
    question = 'Type your surname: '

    def handle_request(self, request):
        if request.handler_name == self.handler_name:
            return self.question
        elif request.handler_name == self.handler_name_answer:
            global store
            store('surname') = request.surname
            del request.surname
            request.handler_name = 'name'
            return self.next_handler.handle_request(request)
            return self.next_handler.handle_request(request)

class NameHandler(BaseHandler):
    handler_name = 'name'
    handler_name_answer = 'name-answer'
    question = 'Type your name: '

    def handle_request(self, request):
        if request.handler_name == self.handler_name:
            return self.question
        elif request.handler_name == self.handler_name_answer:
            global store
            store('name') =

user_request = Request()

chain = PersonIdentifier()

# first ask for surname
user_request.handler_name = 'surname'
surname = input(chain.handle(user_request))
user_request.handler_name = 'surname-answer'
user_request.surname = surname

# then ask for name
name = input(chain.handle(user_request)) = name
user_request.handler_name = 'name-answer'


It looks ugly for me. What do I dislike more is using handler_name and handler_name_answer.

May be you could offer nicer way to solve my task?