I am fairly new to writing modules and have never released one to CPAN. However, I believe I may finally have come up with one that may be useful. I'd appreciate comments and suggestions as to if I should release this or not.
What I have created is a small class that will return an object placeholder. The first time the object is used, it will mutate itself into the actual object, and then proceed with the action that was called.
One place that I am using this is to create a database handle. It probably stems mostly from poor programming style, but there are probably others out there who are lazy and do this as well. Early on in a script a connection to the database is established. However, it may be several seconds or even minutes before the first query is performed. Since the script is executed often, this results in numerous connections to the database that are not doing anything most of the time. This is how the solution works:
use Object::Virtual;
$dbh = Object::Virtual->connect('DBI', $data_source, $username, $auth,
+ \%attr);
sleep 120;
$dbh->do($statement);
# behind the scenes, $dbh is mutated from a virtual object into the ac
+tual database handle, and then the statement is done
I realize that this has some negative aspects. It is no longer possible to check if the database connection was established correctly or not, since the virtual object will always succeed.
It does have some positives as well. In one script, 50% of the time I need to interact with a database. Instead of having to work around making the connection when it is needed, I can just create the virtual object. Then if it is never actually used, the connection is never actually made. It makes the code easy to read, and it doesn't load the database more than is necessary.
Is this something that sounds like it may be useful to other people as well?