SYNOPSIS

 package MyLazyObject;

 use Object::Realize::Later
    becomes => 'MyRealObject',
    realize => 'load';

DESCRIPTION

The Object::Realize::Later class helps with implementing transparent on demand realization of object data. This is related to the tricks on autoloading of data, the lesser known cousin of autoloading of functionality.

On demand realization is all about performance gain. Why should you spent costly time on realizing an object, when the data on the object is never (or not yet) used? In interactive programs, postponed realization may boost start-up: the realization of objects is triggered by the use, so spread over time.

DETAILS

About lazy loading

There are two ways to implement lazy behaviour: you may choose to check whether you have realized the data in each method which accesses the data, or use the autoloading of data trick.

An implementation of the first solution is:

 sub realize {
     my $self = shift;
     return $self unless $self->{_is_realized};

     # read the data from file, or whatever
     $self->{data} = ....;

     $self->{_is_realized} = 1;
     $self;
 }

 sub getData() {
     my $self = shift;
     return $self->realize->{data};
 }

The above implementation is error-prone, where you can easily forget to call realize(). The tests cannot cover all ordenings of method-calls to detect the mistakes.

The second approach uses autoloading, and is supported by this package. First we create a stub-object, which will be transformable into a realized object later. This transformation is triggered by AUTOLOAD.

This stub-object may contain some methods from the realized object, to reduce the need for realization. The stub will also contain some information which is required for the creation of the real object.

Object::Realize::Later solves the inheritance problems (especially the isa() and can() methods) and supplies the AUTOLOAD method. Class methods which are not defined in the stub object are forwarded as class methods without realization.

Traps

Be aware of dangerous traps in the current implementation. These problems appear by having multiple references to the same delayed object. Depending on how the realization is implemented, terrible things can happen.

The two versions of realization: