+---+
+--| A |<-+
| +---+ |
| +---+ |
+->| B |--+
+---+
How can I create A, if to do so I need B, which in turn needs A. The recursive sprial of death soon results if you try to do this with IOC (actually I catch it now and throw an exception, but you get the idea). Also keep in mind that we are talking about classes here, and not instances, with instances you can get really messy.
This problem is solved in other IOC frameworks out there, the Ruby framework called Neddle uses a "deferred" object to do this. Which is basically like our module here. It is a fake Duck until you poke it hard enough, at which point it magically turns into a real Duck.
So using an object like this, one could (in theory) satisfy the above cyclical realtionship. Then A could get a fake B, then B could get a fake A and then all would be well in the world.
This particular module though is a more general approach to the problem in IOC (which will probably use this module under the hood somehow). There are a number of uses I can think of for this this type of module.
The first thing that comes to mind is custom OO-Relational mappers, when mapping table relationships sometimes you dont want to load things right away. (yes, I am sure Class::DBI and its friends can do this, but sometimes Class::DBI is not always a good fit and custom solutions make more sense).
dragonchilds earlier example of deferring DBI is another thought. If your connection costs are heavy and you might not need it then why make it. A more details example might be in a CGI script which checks error conditions first before doing anything to your DB. If you lazyload DBI it could simplify the amount of book-keeping your script needs to do.
There are many possibilities I can see, anything really which has a large cost to being constructed because maybe it uses some outside resources, and which you may or may not need. The result is that your code can be more 'reckless' with your resource intensive objects, while secretly being not-so-reckless.
|