Object-Oriented Design – Where to Put Orchestration Code

designmvcobject-oriented-design

I have a web application implementing the MVC pattern where I have controller classes whose methods each map to an HTTP request.

I also have a service layer with a bunch of service classes, with each service class typically containing operations specific to a particular domain entity.

For simple logic (like CRUD), one controller method typically uses at most one service class and usually only one method on that service class.

My question is how to handle logic that involves two (or more) entities.

The options I see are:

  1. Let one of the existing service classes handle the entire logic.
  2. Create a new service class dedicated to handling logic like this.
  3. Still use the existing service classes but put the orchestration logic in the controller. The controller still delegates the "meat" of the logic to separate services, but it would take care of things like sequencing and deciding at what point(s) to commit changes.

I'm currently favoring option 3 but I would like to know if there is a better way. Please feel free to add any option that I have not yet listed.

Best Answer

An important guideline in deciding where to place code is to keep all code in a single class at the same level of abstraction. In your case, in a typical MVC application the controller operates at a level of abstraction where it makes connections between components and transfers data between them. If an existing service class has a similar level of abstraction then it may be a good fit there, but by your description ("orchestration" sounds like it manages the existing services rather than doing similar things to what they're already doing) it doesn't. So I would suggest creating a new class for it.

Related Topic