views:

2680

answers:

25

Hi,

I am in sort of a dilemma (in a geekish way of course).

I love to declare variables at the beginning of my methods, and usually order them in some logical way.

The problem is, when the list gets long, it sort of gets out of hand.

Should I just declare them when I need them?

+21  A: 

If the list gets long, it is a sign that the method does too much work so you need to split it in two.

Same story with classes and fields.

But I like to put them at the top. Preferably with a piece of comment on their purpose.

Gamecat
I would agree with this.
Huntrods
Agree with splitting; disagree with top. +1 anyway.
strager
+8  A: 

Yes, declare them when you need them.

Grant Wagner
Supported by Code Complete. Steve Mcconnell considered the life of a variable in a method a type of scope, and all variable management is an exercise of reducing scope to its logical limit.
Corbin March
If you get the chance I'd say read the book.. Mind you do it while on vacation. The ideas stack up on themselves.
baash05
+27  A: 

My two cents:

  • Declare variables that are used through-out the function at the top.
  • Declare variables that are used in only a small part of the function at the point where they are needed.
cagcowboy
Not all languages have this feature, but you have a point ;-).
Gamecat
My company (using C++) has a policy of enclosing variables used in only a small part of the function in braces, giving them their own scope. At first I hated this practice, but it has grown on me as a way of organizing code. I think they started doing it due to a few methods that got a bit long...
rmeador
Variables that are used throughout the function will automatically get declared at the top. You don't need a special case for that. ;)
jalf
rmeador.. I work at a place that does the oppisit. I do it but sometimes I get kick back.. I then point them to code complete (a book they purchased for me)
baash05
"Declare variables that are used through-out the function at the top." - I would disagree with that. Always declare variables when they are needed, not before.
Jon Tackabury
+6  A: 

Declare variables close to where you need them. If your function is getting too long, you probably ought to see if it needs to be refactored into smaller, more specific, functions. Remember, the key is coherent readability of your code.

j0rd4n
+107  A: 

Variables should be declared as close to where they are used as possible.

James Curran
dang, can't do +3
Marcin
Also, it often allows you to initialize them at the declaration point for fewer bugs.
Darron
+1 was going to say the same
Robert Gould
I couldn't agree more. I hate seeing a pile of variables declared at the top of a method - that's just sloppy.
Jon Tackabury
+1 here, but also what Gamecat Said "If the list gets long, it is a sign that the method does too much work so you need to split it in two."
Binary Worrier
Agree with Binary W - if you have a list of variables in your function so long that you can order them "logically" then it's time to split up your function.
Richard Ev
Keeping things together is also much more readable, and it makes it easier to clean up unused variables when refactoring.
Rolf
A: 

If I remember correctly the K&R book says to declare a variable close to where you'll be using it. I have done both in practice, though.

Chris Kloberdanz
Paul Tomblin
Kristopher Johnson
+8  A: 

I would say that if your methods are so long that you actually need to differentiate between the two, you may want to consider refactoring.

I personally like to keep them close to where they are used, so their purpose is fresh in my head. However, I think this comes down to programmer preference.

Rob Cooper
+1  A: 

You should in general try to keep them limited to the scope in which they are needed. This fits nicely with the concept of RAII (another answer provided gives a good link for details), and keeps you from having to waste time searching for the declaration of the variable in question.

However, this does not limit you to declaring them at the top or only right where they are used. I view that as an issue of preference for either you or your coding team. With either approach, consistency is key.

Brian
+13  A: 

Your local variables should have absolutely no more visibility than required - so declare them when you need them, and let them go out of scope when you're done with them.

The classic case of this is C++ loop variables:

//BAD - old, C-style:
int i;

for (i=0; i < 100; ++i)
{
...
}

.. vs..

//GOOD

for (int i=0; i < 100; ++i)
{
...
}

One benefit of the reduced scope which isn't immediately obvious is that the following code now fails to compile:

for (int i=0; i < 100; i++);
{
  printf("loop %d\n", i);
}
Roddy
I generally write short methods so it is pretty moot. The iterator i is a poor example in my opinion.
Tim
I disagree that an iterator is a poor example. There are frequent situations where more than one iterator is required in a given method, nested or otherwise. Which is a situation where badly managed variable scope can get in the way of code readability.
Steve Brouillard
++Roddy. This is a great tip. Who has had to go through code where the variable 'i' was used over hundreds (or more) lines of code and multiple loops? I know I have. Another great scope trick (in C++) is pointer variable scope within if statements: if (float* eip = this->getEip()) { /* use eip */ }
Justin
+5  A: 

Never declare a variable until the point where you initialize it. This reduces the opportunities to have bugs due to uninitialized variables.

Kristopher Johnson
+2  A: 

The orthodoxy on coding clarity is that you should declare near first use. If you're following the other orthodoxy about keeping your function/methods short, though, then any declaration will be near its first use. Problem solved ;-)

bradheintz
+3  A: 

I get the sense that declaring variables "at the top" is only a common "style" decision because C90 required it.

Now that you're free to choose, you should probably wait until you need it. Your code should be more readable that way.

ojrac
+7  A: 

Your variables should have the smallest possible scope allowed by the language. (C used to require all variables to be declared at the beginning of a function block. No sane language requires this, because it is a terrible idea.)

A larger than necessary scope means:

  • The code gets harder to read, because I can't see the variable declarations anywhere near where they're actually used, and vice versa.
  • The code gets harder to optimize for the compiler, because every variable could potentially be used anywhere in the function. If it is declared immediately before use, the compiler can at least easily see that it isn't used before then. And if it is declared in a nested scope in the function (For example inside a loop), the compiler further knows that the variable is not used after the loop either.
  • You get a greater chance of name collisions. (A canonical example might be the 'i' loop iteration variable. If you have two for-loops in your function, they can't both use an 'i' variable, unless either
  • They reuse the same variable (which confuses both the reader and the compiler)
  • One of them use a differently named variable (now you have to declare both 'i' and 'j' at the top of the function.
jalf
No - C never required them all at the beginning of the function; they did, however, have to appear at the beginning of some block.
Jonathan Leffler
Thanks for the correction. Fixed :)
jalf
I don't see why using trash variable like 'i' for distinct for-loops is confusing.
Lance Roberts
Reusing the same variable, you mean? It makes it harder for the compiler to optimize your code, and it may make it harder to read for humans as well (When outside the loop, where was the last assignment to i, and what is its value now?).Not a huge issue, but why not just declare it where it's used?
jalf
+2  A: 

I suggest declare a variable based on the usage scope. If used throughout the method..top is good..if something like a temporary holder..closest to its usage. In this way you will always declare closest to the usage...don't forget to indent and space out your code for readability.

Cheers!

Perpetualcoder
Methods shouldn't be long enough to have a "top"
Binary Worrier
+2  A: 

Depends on what language you're using.

Languages like JavaScript do not have block scope. With JavaScript you probably want to declare all your variables used in a function at the start of the function body.

Adam Kahtava
+1 just want to give this answer myself. Why isn't that upvoted more often?!?
Tim Büthe
A: 

Just to add to what has already been said. As a general rule my Methods fit on about one page. If it's getting longer than that, I refactor. That being said, good advice on this page.

Atømix
A: 

I usually declare them where they are needed.

But there's a way where you get the best of both worlds: keep your methods as short as they should be (no longer than 10-15 lines). This way the difference won't be too large.

Joachim Sauer
+3  A: 

Right where you need them. That way they may never need to be instantiated if the code branches a different direction and never needs the variable.

Brian Behm
A: 

I tend to believe that you should allocate variables at the beginning of whatever uses them. If you find yourself declaring variables significantly distant from the beginning of the method where you're using them (unless they're class variables, of course), then I take that as a sign that my method's doing far too much! Really, generally, I try to keep my methods very compact; of course you're going to have variables that get declared in nested scopes, but in general, if I find myself declaring variables far down the method body, I realize that my method is just too damn long.

McWafflestix
A: 

Back in the good-old-days, all variables were declared at the top because the compiler/system needed to account for all of them before doing anything else. That is obviously no longer the case.

My preferences is to ...
a- Declare each variable at the top of the section of code where it is used. If there are too many variable, that is a clue that the section of code can be broker into smaller pieces. I do not like to see declaration statements among the logic; I find they clutter the code and make it harder to understand.

b- Use descriptive names along with a type indicator if it isn't clear, so that it is clear what the variable is and what it is doing. In particular, do this for work variables and variables used for converting things.

Have fun!

tomjedrz
A: 

if it is C code, you have to declare them at the top.

rev
Not true since C99 standard was adopted.
Kristopher Johnson
A: 

My personal preference is to place any globals in a block at the top of the code, and place locals as close as possible to their own scope.

J.T. Hurley
A: 

Declare variable in the beginning of the block.

If it used in only a small part of the function, create a block with { } and declare the variable in the beginning of block. Then I can trace the scope of the variable easily, and GC friendly.

Dennis Cheung
A: 

I've always been a top-of-the-block kind of guy, but lately, I'm moving to throughout my code. I think it's really an irrelevant personal preference (sincerity intended).

As for all the comments about your long list of variable declarations is an indication you need to refactor your code. This may be the case, but not necessarilly. When your current function design does make sense, you may find that many of those variables might fit nicely into a struct or thier own class. This will help clean up your code a bit.

John MacIntyre
A: 

I have all my variables declared at the top. I've read through enough code where variables are declared mid-code that I don't want to play "hunt for the declaration" again. While I'm actively working on a function, variables are scattered whereever they are used; once the function works, I take a pass and bring the variables up to the top and do some commenting - "others-ready code", basically.

Paul Nathan