simple, practical example of "code-reuse with the help of OOP"


Rainer Weikusat

One of the problems "with OOP" is that realistic examples of its use are
usually much too complicated to make good examples and that 'the usual
contrived examples' (eg, drawing shapes or dealing with animals or cars)
are too 'contrived' to be of much use. By chance, I came accross a
'real' simple example.

The problem I had to deal with was uploading a large file for processing
to an appliance with 'very limited' disk space. Because of this,
processing was supposed to work 'from the network', ie, without creating
an intermediate temporary file.[*] offers an 'upload hook
function' feature which can be used to handle the data as it arrives. An
additional complication was that the values of some other fields of the
same form needed to be known before the data could be processed. Clients
are required to send form fields in the order they appear in the form
so, theoretically, putting the other fields in front of the file upload
control should work.

[*] I spend more than half of my 'professional life' buried
below heaps and heaps of variably grotty Java code and thus
rejoice in every opportunity to use simple solutions to simple
problems ...

However, in practice, processes all input data during execution
of the init-method which is invoked immediately before the constructor
returns, meaning, there's no way the 'upload hook' function could use
the CGI object to access the other parameters. Simple OOP-solution for
that (code copyright my employer, cited for educational purposes):

package MAD::RestoreCGI;

use CGI qw(-no_xhtml);
our @ISA = qw(CGI);

#* variables
our $delay_init;
my %inits;

#* methods
sub new_hull
local $delay_init = 1;
return $_[0]->new(@_[1 .. $#_]);

sub init
my $args;

if ($delay_init) {
$inits{$_[0]} = [@_[1 .. $#_]];

$args = $inits{$_[0]};

return $_[0]->SUPER::init(@$args);

# Ziegenzahn-Aschenbecher

The code using this invokes the new_hull ctor which returns the CGI
object but prevents the actual init-method from being executed from the
constructor itself. The init-method is then invoked explicitly to
process the CGI input after the object has been made available to the
upload-function which can then read the 'relating processing parameters'
via $cgi->param('...') in the 'usual' way.

NB: I don't claim that this is a particularly pretty or 'well-designed'
solution, but it is simple and works.

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Latest member

Latest Threads