views:

108

answers:

2

I want to use a DB Singleton i created, in several Methods of a Class. Is it more appropriate to Instantiate the Singleton individually in each Method, or to Instantiate it through the __constructor() and access it from a variable in each method?

Thanks.

A: 

Is the singleton such that it's likely to be used every time you instantiate the class? Or is it only used occasionally on methods that aren't always called? If the former, it's probably more straightforward to do it in the constructor; if the latter, then efficiency would suggest only instantiating it on-demand in each method (this is assuming the overhead of the initial singleton creation is significant - if it's not, just do it in the constructor and save yourself some hassle).

Amber
+3  A: 

Considering it's a singleton, the result will be the same : there will be only one instance of your DB object, and it'll always be the same.

So, both solutions will work, and produce the same result ; at least, if your DB class is used every time an instance of your class is created -- and, of course, the performance difference will probably be negligible.


Still, going with the solution of getting the singleton instance in the constructor and using a class variable in the other methods has an advantage : your methods will not depend on this singleton, but only on a class variable...

... Which means Dependency Injection will be much easier (you'll only have to modify your __construct method, and not each method of the class) if you want to use it one day -- for instance, to "Mock" your DB class, for automated testing purposes.

For more informations, you can take a look at this blog post : What is Dependency Injection?

Pascal MARTIN
Thank you for such a detailed answer :)
bennn
You're welcome :-) Have fun !
Pascal MARTIN