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?

Replies are listed 'Best First'.
Re: Object::Virtual?
by Corion (Patriarch) on Jul 09, 2003 at 19:13 UTC

    How does your module differ from Object::Realize::Later? Please do also document this comparision your documentation, as O::R::L is the only module in the vincinity, and I really like comparisions between modules - they help me decide easier which module to choose / to evalue closer.

    Update: s/Class/Object/g, thanks to lachoy

    perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
      I think you mean Object::Realize::Later which Mark gave a lightning talk about at YAPC::NA 2003.

      Chris
      M-x auto-bs-mode

Re: Object::Virtual?
by mojotoad (Monsignor) on Jul 09, 2003 at 21:37 UTC
    Ima::DBI does this, and so does Class::DBI by virtue of inheritance from Ima::DBI. These are of course specific to dbi, so perhaps a more generic approach is of value.

    Matt