9

The RAII (Resource Acquisition Is Initialization) is one of the suggested ways of constructing objects. How does it relate to the unit testing principles that are saying: no complex job done in the constructor? And especially no explicit creation of objects by "new" operator? However creation of some objects requires some more complex steps sometimes, and passing a factory to a constructor makes the API "dirty" in the meaning of decreasing the legibility. What are the general ways of meeting both of the principles at the same time?

I have found the other topic on SO: Stack allocated RAII objects vs DI principle, however it looks like a more general problem and it is not explained well.

Community
  • 1
  • 1
thatsme
  • 325
  • 1
  • 2
  • 10
  • @MartinJames why? It sounds like a legitimate software design question to me. Moreover, I can't think of any class that'd ask this as homework. – Benjamin Gruenbaum May 02 '14 at 19:58
  • If this is an assignment question then I want to study there! However it's an issue that I meet in every day work. I would like to meet the opinions and the ways the other developers handle it. – thatsme May 02 '14 at 20:01

1 Answers1

7

Yes, creating a concrete class in a constructor complicates the class that does so, adds a dependency to the class, and makes it harder to test.

But, RAII isn't a way of constructing objects, but of releasing resources. The class whose destructor releases the resource doesn't have to construct the object, although it usually does: see What is meant by Resource Acquisition is Initialization (RAII)?.

So, create the resource outside the class that uses it if you want, use a factory to do so if you want, etc., but then let the class that uses the resource clean it up with RAII.

Community
  • 1
  • 1
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
  • Actually at certain moment I have regreted I asked this question as the perfect example of such behaviour is shared_ptr. – thatsme May 03 '14 at 15:35