[[don_t_define_all_local_variables_at_the_top_of_your_method]] Programming Don'ts

Route:

Sometimes you'll see a method that looks like this:

public void method(int a) {
int x; int y; ... //not using x or y x = a + 5; ... //not using y while (...) { y = ... } ... //not using y
}

As you can see, all local variables are defined at the top of the method and used later. Those that code this way tend to think of this as a programming style
but really it's hard to maintain and can be a source of bugs. Imagine you're looking at this code for the very first time and you're trying to understand
what it does. Every time you see a variable used and you ask yourself, "Is this a local or instance variable?" or "what type is this variable?", this way of
programming guarantees you have to lose your place and look at the top of the method to find your answer. If you define your local variables as close
to their usage as possible, there will be many situations where you don't have to do this.

Assume that y's state is not needed outside the while loop. y has a larger scope than necessary in this code. It could have been defined and
initialized inside the while loop but because it wasn't, it could be used before and after the loop. Here's why this is a problem:
Pretend this method has a bug in it and you know that the cause of it is after the while loop. If you're looking at this the first time, you'll likely
waste time discovering that y is only used in the loop and therefore couldn't possibly be the culprit of the bug. You wouldn't have had to discover that
if y was defined inside the while loop. Doing that guarantees it's only used in the loop.

This code can be a source of bugs. Link Statistics show that the chance of bugs increase as the distance between variable declaration and usage increases.
Here is a better way to write this code:

public void method(int a) {
... //not using x or y int x = a + 5; ... //not using y while (...) { int y = ... } ... //not using y
}

don_t_define_all_local_variables_at_the_top_of_your_method, Rev. 3, Last changed on 2008-01-10 20:39, 150 page hits
Help others to find those things you like

Have you already seen the new Tag it! button on the top right of the wiki pages?

Look into the tag cloud
Wiki hosted for free at wikihost.org || RSS-Feed || GeboGebo 1.3.3 || 01.478 seconds || || PAGERANK TOOLS