I have 300 lines of codes that are used roughly twice. Some of the lines
have delicate difference in execution (e.g. ~6 variables have to be replaced
and conditional statements are also different) and therefore many arguments
need to be passed into it in order to differentiate the execution parts. OO
development is analogously also difficult. I wonder if there is any good way
to reuse the codes, e.g. some sort of "goto" rather than duplicating these
lines. Whenever there is any change, I find that is really error-prone.
I have a suggestion. Since you didn't post a coding sample, my
suggestion may not be appropros, but maybe it will.
First, you surely don't have a function that is 300 lines long. If you
do, I don't think I can help. You probably have batches of lines that
are duplicated. The first thing I would do is abstract these batches
of lines into separate functions and call them separately, like this:
&batch_a;
&batch_b;
&batch_c;
sub batch_a { #first batch of lines
}
sub batch_b { #second batch of lines
}
sub batch_c { #third batch of lines
}
Second, you can pass different parameters into these functions to
account for the different variables. If you need to set a variable as
a result of some behavior, set the variable by calling a function,
like this:
$var = &setvar;
sub setvar { #code here sets a var which you would return
return $var; }
Third, you can replace your conditional statements with booleans and
set them outside the function call, like this:
my $conditional = 0
$conditional = 1 if &some_function_that_returns_true;
$contitional = 0 unless &some_function_that_returns_true;
if ($conditional) { #code to execute
}
Fourth, if possible, place your common code (our variables and
functions) in a PM and import the backage. This way, you can separate
the interface and the functionality, and this will also allow you to
refactor your code if and when you have the time to do so. You don't
need to create classes and objects to do this.
Fifth, as a strength building exercise, you might attempt to place ALL
your code, every line of it, in user defined functions and execute the
program by the judicious call of these functions. Of course, you would
still need to declare your lexical variables, but you set them by
function calls.
CC