Sometimes you can write redundant code such as :
sub doSomething
{
...
return 0;
if (@_) { ... }
...
...
}
In this situation, everything after the return statement in the sub will never run. So, it's dead code. It's a good idea to eliminate dead code from a program. Also, consider this example:
for (my $i = 0; $i < 2000; $i++)
{
last if ($i & 1024);
...
}
In this for loop, it appears at first that we count from zero to 1999. But that's not the case. We exit out of the loop when $i == 1024, so you might as well remove that if statement and just make the for loop shorter. This is true assuming that other things in the loop aren't going to be affected by this. And in this case, it's perfectly safe.
Now, let's look at the if () else structure combined with return statements:
if ($MyVALUE)
{
return 4;
}
else
{
return 5;
}
The problem here is that the "else" statement is unnecessary, because this would accomplish the same thing as this code:
if ($MyVALUE) { return 4; }
return 5;
This code could be even further simplified to:
return $MyVALUE ? 4 : 5;
See? We started out with 8 lines of code, and we reduced it to just one line. Now, this is not always a good idea, because if shortening the code causes it to become harder to understand, then it may not be a good idea. But usually if you can write shorter code that does the exact same thing, then the shorter is better.
Here is an example where shorter code makes things harder to understand. Example A and B and C all do the exact same thing, but example B and C are harder to read. And being able to read code is important too:
my $A = 0;
my $B = 0;
my $C = 0;
# EXAMPLE A:
if ($V == 0) { $A = 5; $B = 39; $C = 0; }
elsif ($V == 1) { $A = 0; $B = -1; $C = 188; }
elsif ($V == 2) { $A = 101; $B = 18; $C = 19; }
# EXAMPLE B:
my $LUT = "\6(\1\1\0\xBDf\x13\x14";
$A = vec($LUT, $V*3, 8)-1;
$B = vec($LUT, $V*3+1, 8)-1;
$C = vec($LUT, $V*3+2, 8)-1;
# EXAMPLE C:
($A,$B,$C)=map($_-40,unpack('x'x($V*3).'CCC',"-O(('\xe4\x8d:;"));
If instead of $A $B and $C we could use much longer variable names, you would see that example A becomes much much longer, but it is still easier to read, so I think that is better (unless your goal is to write code that no one understands). lol We can write something in fewer keystrokes, but it would just become more complicated. GrandFather's signature "Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond" has a lot of truth in it. ;)
Consider this: 5-10 years go by and you open your perl script to read your own code. And if you write like in example A, you will understand it immediately. But if you code like in example B or C, you will be pulling your hair out. lol |