Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share

migration rejected from stackoverflow.com Dec 5 '13 at 4:27

This question came from our site for professional and enthusiast programmers. Votes, comments, and answers are locked due to the question being closed here, but it may be eligible for editing and reopening on the site where it originated.

closed as primarily opinion-based by gnat, GlenH7, MichaelT, Bart van Ingen Schenau, Greg Hewgill Dec 5 '13 at 4:27

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

comments disabled on deleted / locked posts

22 Answers

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

share
2  
Also, it often allows you to initialize them at the declaration point for fewer bugs. –  Darron Nov 25 '08 at 22:26
12  
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 Nov 26 '08 at 13:01
3  
+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 Nov 27 '08 at 13:27
8  
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 Everett Nov 29 '08 at 11:09
6  
Keeping things together is also much more readable, and it makes it easier to clean up unused variables when refactoring. –  Rolf Nov 30 '08 at 12:56
show 3 more comments

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.
share
21  
Variables that are used throughout the function will automatically get declared at the top. You don't need a special case for that. ;) –  jalf Nov 25 '08 at 22:18
9  
"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 Nov 26 '08 at 13:03
show 3 more comments

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.

share
7  
Agree with splitting; disagree with top. +1 anyway. –  strager Nov 28 '08 at 4:42
show 1 more comment

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++); // <--- Note the trailing ';'
{
  printf("loop %d\n", i);
}
share
3  
++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 Nov 30 '09 at 22:48
show 3 more comments

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.
share
show 4 more comments

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.

share
add comment

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.

share
2  
+1 just want to give this answer myself. Why isn't that upvoted more often?!? –  Tim Büthe Aug 13 '10 at 12:41
show 1 more comment

Yes, declare them when you need them.

share
show 2 more comments

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.

share
add comment

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

share
add comment

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.

share
add comment

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.

share
add comment

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 ;-)

share
add comment

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.

share
add comment

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!

share
show 1 more comment

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.

share
add comment

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.

share
add comment

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.

share
add comment

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!

share
add comment

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.

share
add comment

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.

share
add comment

This is a rather simple question in regards to variable declaration and there location to which they are declared.

I take on the following rules which to me makes sense for readability sake:

  • if you have a for loop, declare the variable on the same line, i.e.for(var i = 0; i < ....; i++)...
  • if there is a need to use a variable to reference a value that is being looped over inside a for or while block which also needs to be re-declared on each loop, declare the variable inside the block '{}'
  • declare all other variables at the top of the function using a comma separated list with a single var statement.

if the variable list gets too big then re-factor and move functionality into a separate function referencing that newly created function.

if the functionality is only used for that method then think of the possibility of having an inner function that then declares the variables to do with that function inside that function.

function A(){
    var a, b, c;
    function B(){
        var d, e;
        // code here
        return false;
    }
    b = B();
    return b;
};

If you have the need to have multiple inner methods/functions then think of organising them into an object literal such as the following:

To note I am using a self invoking method to return an object literal of functions but also giving it the capacity to have private members.

var method = (function(){
    // some private variables maybe?
    return {
        getBob : function(){
            return 'bob';
        },
        addTwo : function(n){
            return n + 2;
        }
    }
}());

v1 = method.addTwo(25) // returns 27

rebecca murphey (http://rmurphey.com/) once said in a pod cast that she prefers to use a function expression instead of a function declaration - this however she said is for personal reasons, although it would make sense to use an expression due to function declarations always being loaded first - in my view it gives greater control of what loads and when; but of course I have used a function declaration in the example, this is more for illustration purposes rather than a necessity.

I added some more to this, it may have gone off from the original question but I still think it is relevant.

Hope that makes sense.

share
1  
you are declaring b twice. You seem to be using javascript where hoisting makes those rules not very useful. Could you explain why you think this is a good idea? –  Simon Dec 4 '13 at 16:40
show 1 more comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.