Fork me on GitHub
Skip to content
Jul 5 11

Scratching your left ear with your right hand

by anthony

There are many ways to do many things in the computer world as evidenced by xkcd #763.  When in programming classes at the university, my professor would see some of the silliest things.  He had a very nice way of telling classmates they’re doing things wrong; he would tell them their code was, “like scratching your left ear with your right hand.”  Go ahead and try it.  Sure, it works, but there’s a better ways to do things.

xkcd: Workaround

xkcd: Workaround

Now, I don’t profess to be a coding master leet hacker guru.  I do, however, understand that there are a few things that could definitely be more optimized with this code below.  Sure, it will work.  Sure, it should have the correct and desired outcome, but there are a few ways to do things a bit differently.  In something small, it’s not going to have a huge impact.  Do this a few dozen unnecessary times, and you may have issues.

Professional coders, this post may be of no use to you, or maybe it’s a nice refresher on some coding style.

We’re going to break down a small block of code I recently saw.  Granted, this is psuedocode, but you get the point of what was actually happening:

int $theStart = 0;
for ($theStart=2012; $theStart < 2028; $theStart++)
{
//do some operation (2028-2012 times)
}

First  off, you’re hardcoding limits into your forloop. Don’t do this, it makes babies cry.  To make this more flexible, I recommend variables declared at the top of the class/function/whatever-block-is-currently-in-scope with some lower and upperbound that is easily identifiable.

Remember this line?

int $theStart = 0;

Well, you’re re-declaring the variable the next line. That’s just silly.

for ($theStart=2012;  $theStart < 2028; $theStart++)

Because you’re re-declaring $theStart here, we’re going to combine that with the declared lowerbound and upperbound into this:

int $lowerBound = 2012;
int $upperBound = 2028;
for (int $i=$lowerBound; $i < $upperBound; $i++)
{
//do some operation ($lowerBound - $upperBound times)
}

You can probably see that it may be one more extra line of actual code, but here’s an explanation of why this is better.

  • We’re avoiding re-declaring an already declared variable
  • Easily identifying upperBound and lowerBound variables, if you need to change them later, resuse this code for anything else, adjust this class/block/function to take in upperBound and lowerBound as arguments, etc
  • Makes the code easier to work with using the temporary variable i inside the forloop, instead of worrying about changing theNumber. Granted, theNumber‘s actual value won’t change outside of this forloop (scope, kids!), but it still won’t be as confusing.

Take what you want out of this, perhaps it’ll help some code out there be better, stronger, run faster, and jump higher.  Also, try using your right hand to scratch your right ear.