1

I´m working in a code which follows some steps, and each of this steps is done in one class. Right now my code looks like this:

use step_1_class;
use step_2_class;
use step_3_class;
use step_4_class;
use step_5_class;
use step_6_class;
use step_7_class;
...
use step_n_class;


my $o_step_1 = step_1_class->new(@args1);
my $o_step_2 = step_2_class->new(@args2);
my $o_step_3 = step_3_class->new(@args3);
my $o_step_4 = step_4_class->new(@args4,$args_4_1);
my $o_step_5 = step_5_class->new(@args5);
my $o_step_6 = step_6_class->new(@args6,$args_6_1);
my $o_step_7 = step_7_class->new(@args7);
...
my $o_step_n = step_n_class->new(@argsn);

Is there a cleaner way of declaring this somewhat similar classes wihtout using hundreds of lines?

nck
  • 1,673
  • 16
  • 40

2 Answers2

3

Your use classes as written are equivalent to

BEGIN {
    require step_1_class;
    step_1_class->import() if step_1_class->can('import');
    require step_2_class;
    step_2_class->import() if step_2_class->can('import');
    ...
}

This can be rewritten as

BEGIN {
    foreach my $i ( 1 .. $max_class ) {
        eval "require step_${i}_class";
        "step_${i}_class"->import() if "step_${i}_class"->can('import');
    }
}

The new statements are a little more complex as you have separate variables and differing parameters, however this can be worked around by storing all the objects in an array and also preprocessing the parameters like so

my @steps;
my @parameters = ( undef, \@args1, \@args2, \@args3, [ @args4, $args_4_1], ...);
for ($i = 1; $i <= $max_class; $i++) {
    push @steps, "step_${i}_class"->new(@{$parameters[$i]});
}
JGNI
  • 3,933
  • 11
  • 21
1

You can generate the use clauses in a Makefile. Generating the construction of the object will be more tricky as the arguments aren't uniform - but you can e.g. save the exceptions to a hash. This will make deployment more complex and searching the code tricky.

It might be wiser to rename each step by its purpose, and group the steps together logically to form a hierarchy instead of a plain sequence of steps.

choroba
  • 231,213
  • 25
  • 204
  • 289