473,883 Members | 1,786 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4005
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*@discussion s.microsoft.com > wrote in message
news:CA******** *************** ***********@mic rosoft.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*@discussion s.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****@communi ty.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.co m>
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
2143
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 efficient than repeatedly referencing the member in a loop? Maybe using a string isn't the best example, but hopefully you get the idea! * example (referencing member):
5
3094
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 user's browser and assign a variable with different items if it's Internet Explorer. My code works with firefox, opera and others but not IE. <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled...
2
1466
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 of these may or may not be used depending on a couple of IF...Then's further down the page... What I'd like to know is - should I declare ALL of my variables at the top like this whether they might be used or not - thus keeping them in one easy
5
9265
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 sub" in a program: dim mydata as (whatever) Public Sub Page_Load(etc..)
17
5544
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 too much - that it's bad programming practice. Is there an easy way to deal with this? I would like to do things in the "Best Practices" way but at the same time I don't want to make a federal case out of it. This comes up over and over...
15
2976
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 is how all the examples I've seen so far create an OleDbCommand Object: Dim cmd as new OleDbCommand("Select * FROM Table1",cnn) I had to figure out that it was the same as this:
10
7044
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, including main.cpp I have global variables that need defining in main.cpp and declaring in all other files in. The way I've seen it done is to define/declare everything in one header file (e.g. globalincludes.h) prefaced with the word EXTERN ...
8
5870
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: // Begin sample for(int i = 0; i < 100; i++) {
8
7528
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, like this: for(var i=0; i<list; i++) { var name = list; }
0
9792
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11142
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10745
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10848
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10417
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9575
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7972
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5798
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3234
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.