2

This is a re-wording of this SO post.

I found that using the mediator pattern is effective at reducing the number of parameters in my controllers.

I then began to wonder if this would be affective domain services.

But wouldn't that hide the dependencies of the service?

I remember reading somewhere that if I have a bunch of dependencies being injected, I probably have a larger domain concept that can be encapsulated in its own service. I found this to be an effective pattern.

So, how do I reduce the number of constructor parameters in the business layer services?

Community
  • 1
  • 1
drizzie
  • 3,351
  • 2
  • 27
  • 32
  • @theDmi Reworded, hopefully I can get some community insight on this one ;) – drizzie Nov 01 '16 at 11:53
  • You should have edited your original question. It's already on the way to being reopened and a significant edit like this would only help speed that along. – ChrisF Nov 01 '16 at 11:55

1 Answers1

5

Too many constructor parameters are a code smell and typically indicate a violation of the single responsibility principle - so you need to take care of that "S" in your SOLID code base.

A constructor parameter is a dependency. By "solving" the problem with a mediator, you will still have the same number of dependencies, just with fewer constructor parameters. You essentially move from a visible SRP code smell to a hidden SRP code smell - not really a step forward.

Improving "too many dependencies" situations

This blog post talks about this exact problem and supports it with an example.

The basic approach to improve your situation is to find code that clusters around a set of dependencies and extract that code into a new service class:

  1. Analyze how dependencies interact to identify clusters of behavior.
  2. Extract an interface from these clusters.
  3. Copy the original implementation to a class that implements the new interface.
  4. Inject the new interface into the consumer.
  5. Replace the original implementation with a call the new dependency.
  6. Remove the redundant dependencies.
theDmi
  • 17,546
  • 6
  • 71
  • 138
  • I agree with this logic. That being said, can't we apply this to API controllers as well? Perhaps we need to breakup the concerns of a our api controllers into more specific controller classes? – drizzie Nov 01 '16 at 20:00
  • 1
    The process of breaking up the concerns and their boundaries can be challenging. As a guide, you can use business terminology and business capabilities. – alltej Nov 02 '16 at 03:36
  • 1
    @drizzie These steps can be applied to any class with too many constructor parameters, even value objects! The only thing that differs is how you name the extracted concept. – theDmi Nov 02 '16 at 06:57