473,386 Members | 1,621 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

declaring variables - best practice

Ant
hi,
I'm now using C#. Seeing as though you can declare & initialize or pass a
value to a variable on the same line as the declaration, is it still best
practice to group all the variables together at the top of the method, or is
it now acceptable for them to be declared at the point where they are
initially needed, seeing as though you can 'go to the definition', with the
right click of a mouse?
Pedantic I know, but I'm curious.

thanks for your opinions

Ant
Nov 17 '05 #1
5 3975
Ant wrote:
hi,
I'm now using C#. Seeing as though you can declare & initialize or pass a
value to a variable on the same line as the declaration, is it still best
practice to group all the variables together at the top of the method, or is
it now acceptable for them to be declared at the point where they are
initially needed, seeing as though you can 'go to the definition', with the
right click of a mouse?
Pedantic I know, but I'm curious.

thanks for your opinions

Ant

Coming from vb6 which did not have "proper" scope for variables I really
like the fact that if you declare a variable within an if block then
that variable is limited to that if block etc..

Personally I always declare when needed, not at the top.

JB
Nov 17 '05 #2
Ant, there's no reason not to be pedantic; these things matter.

Many people believe that variables should be declared at the top of the
scope they need to be visible in.

The compiler doesn't care where they lie, but for visual scans of the code
it seems to help if they're all grouped together at some predictable place
in the code. Encourages you to use some sort of structured commentary
describing them, lets you see them all in a glance, etc. The more visual
structure you apply to your coding style, in fact, the easier it is for a
reader to use our human pattern-matching abilities to extract information
from the source code. And as we all know, it's much harder to read code than
it is to write it.

Many people also believe that you should declare a variable within the
narrowest scope that it's needed in. So variables declared at the very top
of a method are those that are used throughout the method, those that are
used in inner blocks should be declared at the top of their blocks, and so
forth. One good reason for keeping tight scope on variables is that if an
inner block never gets executed on account of a branch condition, the
runtime never needs to exert itself to instantiate it.

C# is highly block-scoped; VB didn't used to be, but now is.

Iteration variables are best declared, according to Microsoft, in the top of
the iteration:
foreach (string s in substrings) ;
for (int i = 0; i <= something; i++) ;
Or if you like VB.Net:
For Each s As String In substrings
For i As Integer = 0 To something

Naturally, I concur with these opinions, after about a million years in this
biz, or I wouldn't be spreading them around.

In practice, of course, I sometimes bend these rules and plunk down a
declaration in medias res, but I always feel a teensy bit uncomfortable when
I do it. And sometimes I go back and move them. But not always.

HTH,
Tom Dacon
Dacon Software Consulting

"Ant" <An*@discussions.microsoft.com> wrote in message
news:CA**********************************@microsof t.com...
hi,
I'm now using C#. Seeing as though you can declare & initialize or pass a
value to a variable on the same line as the declaration, is it still best
practice to group all the variables together at the top of the method, or
is
it now acceptable for them to be declared at the point where they are
initially needed, seeing as though you can 'go to the definition', with
the
right click of a mouse?
Pedantic I know, but I'm curious.

thanks for your opinions

Ant

Nov 17 '05 #3
"" Seeing as though you can declare & initialize or pass a
value to a variable on the same line as the declaration, is it still best
practice to group all the variables together at the top of the method ""

I like to declare & initialize/pass a value to a variable on the same line
as the declaration where i can, and normally at the top of the specific scope
where it is used. I find this helps readability because its fewer lines of
code.
Nov 17 '05 #4
Ant <An*@discussions.microsoft.com> wrote:
I'm now using C#. Seeing as though you can declare & initialize or pass a
value to a variable on the same line as the declaration, is it still best
practice to group all the variables together at the top of the method, or is
it now acceptable for them to be declared at the point where they are
initially needed, seeing as though you can 'go to the definition', with the
right click of a mouse?
Pedantic I know, but I'm curious.


If you can, acquire a copy of Code Complete 2 by Steve McConnell. It's a
great book (I'd call it a 'must-have') which gives advice on things like
this.

The author's idea on this particular subject is that a variable's
declaration should appear as close as possible to its definition, in order
to aid readability. This is then discussed in detail.
Nov 17 '05 #5
Tom Dacon <td****@community.nospam> wrote:
Ant, there's no reason not to be pedantic; these things matter.

Many people believe that variables should be declared at the top of the
scope they need to be visible in.

The compiler doesn't care where they lie, but for visual scans of the code
it seems to help if they're all grouped together at some predictable place
in the code.


I agree with that for member variables, but for local variables I far
prefer to see a variable at the point of first use. That way they are
often self-commenting. For instance:

// The name of the recipient for the email address we're about to
// process
string recipientName;

// ...Lots more stuff in the same scope...

recipientName = email.Recipient;
// etc
isn't as readable to me as:

// Lots of stuff in the original scope...

string recipientName = email.Recipient;

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Oliver Corona | last post by:
I am wondering if anyone has any insights on the performance benefit (or detriment) of declaring local variables instead of referencing members. Is allocating memory for a new variable more...
5
by: fred | last post by:
I don't know if I'm doing this correctly. I have a little programming experience in python, c++ and some others but this is my first time with javascript. I'm trying have my website detect the...
2
by: Rob Meade | last post by:
Hi all, New to .Net - still finding my feet...quick question... In one of my functions I have about a dozen variables being declared at the top - the first thing within the function, about 2...
5
by: Fred Nelson | last post by:
Hi: I'm a relative newby so hopefully this is a simple question! I have found that I can create global variables easily on a web page by placing the dim statement before the first "private...
17
by: Woody Splawn | last post by:
I am finding that time after time I have instances where I need to access information in a variable that is public. At the same time, the books I read say that one should not use public variables...
15
by: CR | last post by:
I've noticed that the trend these days is to declare variables in the middle of code instead of at the top. What is the advantage of this? It seems like it makes it hard to reuse variables. Here...
10
by: Jay Wolfe | last post by:
Hello, I'm trying to make sure I use best practices (and hence save myself some headaches) with the declaration and definition of global variables. Let's say I have an app with 30 files,...
8
by: rendle | last post by:
I have a MSIL/performance question: Is there any difference between declaring a variable once and assigning to it multiple times, and declaring and assigning multiple times? For example: //...
8
by: SM | last post by:
I've always wonder if there is diference when declaring and initializing a varible inside/outside a loop. What's a better practice? Declaring and initializing variables inside a loop routine,...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.