0

I work on a huge legacy project. There are a number of classes that are created basically only once (they should be singletons, but oh well) and then passed around to almost every other class in the program.

So there is lots of code like this where the class has a nearly endless list of pointers in its constructor

Foo(A* a, B * b, C * c, ...) 
   : Foo2(a,b,c),
     _a(a),
     _b(b),
     _c(c),
     ...,
{} 

I was thinking I could clean it up if I used an class to contain all of the pointers and use forward declaration to avoid creating more include dependencies. Each class could use the getters then to pull out anything they needed and include the appropriate headers.

//No includes required
class A;
class B;
class C;
class InterfaceMngr
{
public:
      InterfaceMngr(A * a, B * b, C* c)
       :_a(a),
        _b(b),
        _c(c)
      {
      }
     A * GetA() const { return _a; }
     B * GetB() const { return _b; }
     C * GetC() const { return _c; }

private:
     A * _a;
     B * _b;
     C * _c;
};

So the foo example would look something more like this now

Foo(Interface * inf) 
 : Foo2(inf),
   _a(inf->GetA()),
   _b(inf->GetB()),
   _c(inf->GetC())
{}

The nice thing is whenever a new class API comes into the picture I can just add it to Interface and don't need to change a few hundred constructors again....

Does anyone see an issue with this? I feel like I'm over exposing access to some classes, but it really simplifies editing the code.

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
Jason T.
  • 362
  • 2
  • 11

2 Answers2

2

I think you are looking at the Context design [anti-]pattern.

Community
  • 1
  • 1
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
2

Don't be so quick to lament the lack of singletons. By passing object instances to your constructors, it makes it easier to perform unit tests.

If you are going to aggregate class pointers like that, perhaps you should consider making logical groups instead of one big catch-all interface aggregate. This will prevent having everything be dependent on everything else.

The Facade pattern may be of use to you as well.

Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
  • 1
    +1 for mentioning unit testing, and how singletons make it nigh-impossible. – Bill Jan 27 '10 at 20:02
  • To make unit testing easier with singletons, you can leave yourself a "back door" so that the test harness can switch the singleton instance so that it references something else (like a mock object). But this can start falling apart when you do integration testing. I haven't had much chance to explore this "workaround". – Emile Cormier Jan 27 '10 at 20:11