views:

698

answers:

12

Is there a good reason (advantage) for programming this style

XmlDocument doc = null;
doc = xmlDocuments[3];

vs

XmlDocument doc = xmlDocuments[3];

I have seen it many times but to me it just seem overly verbose

A: 

I would go with

void Foo()
{
  XmlDocument doc;

  //Do other code here

  //Create doc
  doc = xmlDocuments[3];
}

As doc may not be being used till later on in the method. It makes more sense to create doc just before it is used. Easier to read (less scrolling).

Stevo3000
Why not declare doc *at* the point of first use? Even better :)
Jon Skeet
@Jon Skeet - We follow the coding standard that all variables are declared at the top of a method. Makes it nice and simple to see roughly (exactly in VB.net) how many variable are in use.
Stevo3000
Why is it useful to see how many variables are in use compared with seeing the type of the variable *at the point of use*? Declaring variables at the start of the method has been seen as an anti-pattern for a *long* time...
Jon Skeet
@Jon Skeet - Declaring the variable at time of use does not give you an advantage of knowing the type if you are using an IDE as hovering over the variable gives you this as well. If all variable are declared at the top then there is no confusion about the scope of the variable (e.g. using the same variable name in 2 different scopes).
Stevo3000
I'd argue that it *adds* to confusion by encouraging you to use the same variable name for two different meanings - limiting the scope means it's obvious what the variable is used for. As for hovering over the variable: I find code more readable when I don't have to mouse around to understand it.
Jon Skeet
@Stevo3000 Having the declaration at the top also means that the scope of the variable is larger than necessary. That makes the intended use of that variable less clear, e.g. why declare an loop index at the beginning? This simply encourages re-use and makes it more likely that things can go wrong.
0xA3
@divo: That was exatly the point I was going to make. Keep your variables in as restricted a scope as possible as this prevents accidentally using the wrong variables.
xan
+17  A: 

I would use

XmlDocument doc = xmlDocuments[3];

Declare variables where they are used.

Mitch Wheat
+28  A: 

No - it's generally considered best practice to declare a variable as late as you can, preferably setting it at the point of declaration. The only time when I don't do that is when I have to set a variable conditionally, or it's set in a more restrictive scope:

String name;
using (TextReader reader = ...)
{
    // I can't declare name here, because otherwise it isn't
    // accessible afterwards
    name = reader.ReadToEnd();
}

Reasons for declaring at the point of first use where possible:

  • It keeps the variable's type close to its use - no need to scroll back up in the method to find it.
  • It keeps the scope as narrow as possible, which makes the use of the variable more obvious.
Jon Skeet
A: 

I'm always trying to declare and assign variables on the same row if possible, so in this case I would try to use the second option. Fewer lines of code, less declared variables to keep in mind when reading the code also. In the end I think it's all about the coding rules you and your team uses though. We've had coding rules which says to declare all local variables in the beginning of the method, so I've seen both programming styles.

Johan Danforth
A: 

I prefer to use this one:

XmlDocument doc = null;
//blah blah
doc = xmlDocuments[3];

I just want assign and use 'doc' when it is required..

If I want use it right after assignment I go for

 XmlDocument doc = xmlDocuments[3];
Prashant
I would avoid assigning the value to null unless you specifically need to.
Stevo3000
A: 

If the variable 'doc' is assigned right after it is declared then no, I don't see any reason why you would want to do that. In any case, it certainly is not my style.

Razzie
+2  A: 

The declaration and assignment should ideally be paired for code legibility. In fact ReSharper will pick up any exceptions to this and suggest that they be joined.

Troy Hunt
+2  A: 

They are different styles, and neither of them is objectivily better than the other. It's just a matter of taste. You can either declare the variable first and then assign a value to it:

XmlDocument doc;
doc = xmlDocuments[3];

Or you can do both in the same statement:

XmlDocument doc = xmlDocuments[3];

However, this form:

XmlDocument doc = null;
doc = xmlDocuments[3];

To assign a null reference to the variable and then immediately replace it with a different reference, is totally pointless.

Guffa
assign a null reference is not pointless, it's actually damaging, because you don't want to pick up that habit. The compiler will issue a compile error if you use a variable which you haven't assigned. Assigning null will waive that error. And it's often useful to have that error raised.
DonkeyMaster
I assume that you mean that it's not _only_ pointless. :)
Guffa
+1  A: 

As the others has pointed out the first style can be useful if you need to declare the variable outside the scope of a loop, if or something else. But in most cases I think this style is a remnant from the old days of Visual Basic 6 (and earlier) where you always had to declare a variable before using in.

Old VB didn't support your second style and therefore the first style is still popular...

Rune Grimstad
I suspected this was the reason as there does not seem to be any functional reason for doing this.
TT
A: 

I like to think of variables as 'shared' or 'not shared' in that some variables need to be used in multiple locations in the class or method, and some you only need to use once. For the former, I declare them all at the top of the relevant block, the latter I declare just before I use them.

It all depends on where you need to use them.

Case 1:

Xyz xyz = new Xyz; // Declared at the top.
// Loads of unrelated code in-between...
xyz.abc();
// More unrelated code in-between...
xyz.def(stuff);

Case 2:

// Loads of unrelated code above...
Xyz xyz = new Xyz; // Declared in a 'block'.
xyz.abc();
xyz.def(stuff);
xyz.destroy();
// More unrelated code below...
Antony Carthy
Even if a variable is used in several places, why declare it at the top rather than just before the *first* use? Where's the benefit? Declaring it at the point of first use means the declaration and initialization is right there in your face when you're looking at the use of it, leading to better readability.
Jon Skeet
A: 

I agree mostly with Jon (Not to mention that usually I have to agree with him :-).

you have options:

1.

//Do something...
XmlDocument doc = xmlDocuments[3];
//use doc
//Do something...

2.

//Do something...
XmlDocument doc = null;
doc = xmlDocuments[3];
//Use doc
//Do something...

3.

//Do something...
XmlDocument doc = null;
//...Do something with other variables etc...
doc = xmlDocuments[3];
//Do something...
//Use doc

4.

//Do something...
XmlDocument doc = null;
//...Do something with other variables etc...
doc = xmlDocuments[3];
//Use doc
//Do something...

5.

//Do something...
XmlDocument doc = null;
doc = xmlDocuments[3];
//Do something...
//Use doc

6.

//Do something...
XmlDocument doc = xmlDocuments[3];
//Do something...
//use doc

I hope you can see that option 1 makes good sense.

It is best to keep declaration, definition and initialization as "together" as possible. Option 1 is example of declaration, definition and initialization done together in one line. You could compress it further:

var doc = xmlDocuments[3];

Vocabulary (language independent):

  • Declaration: Coder introduces new name to compiler.
  • Type binding: Type inference, use super-type etc.
  • Definition: Coder makes compiler to reserve space. (on stack etc. - note that external names do not need space)
  • Initialization: Coder assigns value first time during definition. Compiler does initialization (to nulls, 0, false, default values etc.) in most cases if coder omits initialization.
  • Usage: Obvious!
  • Scope: Obvious!
  • Accessibility, where applicable. : Obvious!
  • Modifier: Instance level, class level, method level, constant, readonly etc.

I hope this helps.

isntn
A: 

Guess I have been bad for years as typically I setup ALL variables first

// Define object variables string connectionString = string.empty; bla.. bla..

// Get connectionString connectionString = Configuration.Bla["connectionString"]

pinkfloyd