mardi 1 septembre 2015

Reduce constructor arguments whilst keeping service usage explicit?

I am using C#, but my question applies to any OOP language.

I have many different objects that consume a range of services. I would like the way these services are accessed to satisfy a few constraints, but I am struggling to figure out a good design.

  • I would like the usage of these services to be explicit
  • An object should never be in an invalid state (services should be passed on construction)
  • Service usage should be clear
  • Code repetition should be minimal

I think these are all good aims, but they are proving difficult to achieve in practice. My current approach is a sort of dependency-injection-by-hand:

class MyObject(IFooService fooService, IBarService barService)
{
    this.fooService = fooService;
    this.barService = barService;
}

So far so good. But what happens when I have lots of service dependencies? I have dozens of objects, some of which need to access many services.

I considered building a "service container" object and passing that in:

class Services(IFooService fooService, IBarService barService)
{
    this.fooService = fooService;
    this.barService = barService;
}

class MyObject(Services services)
{
    this.services = services;
}

However, this obscures the services that an object actually uses. Given the constructor, MyObject might use any of the them!

  • What are some common approaches to avoiding this problem?
  • Is my problem indicative of a more fundamental design issue?
  • Is this really a problem at all? Should I relax some of my design goals?

Aucun commentaire:

Enregistrer un commentaire