Mar
22
2007
Good Coding: Use More Variables
Don’t be afraid to use more variables if it helps to clarify the code.
Here’s something similar to some code I worked on yesterday.
my $style;
if ( $large ) {
$style = "font-size: 12pt;";
}
elseif ( $medium ) {
$style = "font-size: 8pt;" ;
}
else {
$style = "";
}
$style = "<style>$style</style>" if $style;
Reusing the style variable in this way can lead to moments of confusion when reading the code later on.
Here’s a better way to do the same thing.
my $style_declarations;
if ( $large ) {
$style_declarations = "font-size: 12pt;";
}
elseif ( $medium ) {
$style_declarations = "font-size: 8pt;" ;
}
else {
$style_declarations = "";
}
my $style = "<style>$style_declarations</style>" if $style_declarations;
I find this makes much clearer what the code is doing…especially if the person viewing it is just scanning the code quickly to find a specific section of functionality.
