|
-
Mar 25th, 2005, 01:32 PM
#1
Thread Starter
Lively Member
Variable declaration and naming best practice
1. Is it better to declare variables at the top of the Sub or Function, or is it better to declare them just before they are used?
2. Is it best to still use prefixes e.g intCount?
-
Mar 25th, 2005, 02:02 PM
#2
New Member
Re: Variable declaration and naming best practice
I was always told that it was better to declare your variables at the top of the sub or function, but I've seen less of that and more of declaring them just before being used in VB.NET examples.
It is always a good idea to use a naming convention that helps clarify the purpose and scope of your variables, as in your example.
-
Mar 25th, 2005, 02:11 PM
#3
Re: Variable declaration and naming best practice
Declaration of variables is a compile-time directive - not a run-time directive.
In my opinion they do not belong in the code-logic.
They go at the top of where the scope of the variable belongs - top of SUB or FUNCTION - top of MODULE.
-
Mar 25th, 2005, 03:18 PM
#4
Addicted Member
Re: Variable declaration and naming best practice
For my projects, I follow the guidelines in the excellent book Code Complete. Code Complete emphasizes the value of code readability in software development; code that is easy to read and understand is easy to modify and maintain.
Towards that end, CC recommends that variables be declared in the smallest possible scope, and as close to their first use as possible. This recommendation is supported by research that suggests that doing so places fewer mental demands on the person reading your code.
For example, declaring a loop variable just before the loop.
VB Code:
Dim MyCounter as Int32 = 0
While MyCounter < 10
' some code here
End While
VB.NET also introduces Block Scope, where a variable declared inside any structure with an End statement only exists inside that structure. For example...
VB Code:
If SomeBoolean = TRUE then
Dim MyString as String = "Some Error Message"
MessageBox.Show(MyString)
End If
In the above code, the "MyString" variable does not exist and is not visible outside of the If...End If block. This improves code readability in two ways. First, someone reading the code knows that MyString only exists inside the If...Endif block. Second, I don't have to declare MyString at the top of my procedure when it's a variable of trivial importance.
CC talks about the concept of "Live Time" - the number of lines between the first time a variable is mentioned and the last time it is used. Research shows that shorter variable live times translate into code with fewer defects - shorter live time means less opportunity for initialization errors, or for some other code to muck with the variable.
This issue is a very subjective one, and there's no one right answer. My experience has been that applying the Code Complete guidelines (and insisting that the programmers that work for me apply them) has resulted in significant and tangible improvements in the readability and quality of the code that my department produces. It also makes it easier for programmer #1 to pick up where programmer #2 left off when workloads need to be shuffled.
As to your second question, using prefixes, this is also a personal choice. The Microsoft .NET Naming Guidelines recommend not using prefixes for most object names. .NET's strong typing makes it less necessary, and coding with Option Strict On will prevent your code from compiling if you try to implicitly cast from one type to another. I still use prefixes for toolbox items (buttons, list boxes, and such) but not for data types (strings, ints, arrays, etc.)
Hope this helps!
Last edited by DWRoelands; Mar 25th, 2005 at 03:29 PM.
-
Mar 25th, 2005, 03:29 PM
#5
Re: Variable declaration and naming best practice
 Originally Posted by DWRoelands
For my projects, I follow the guidelines in the excellent book Code Complete. Code Complete emphasizes the value of code readability in software development; code that is easy to read and understand is easy to modify and maintain.
Towards that end, CC recommends that variables be declared in the smallest possible scope, and as close to their first use as possible. This recommendation is supported by research that suggests that doing so places fewer mental demands on the person reading your code.
For example, declaring a loop variable just before the loop.
VB Code:
Dim MyCounter as Int32 = 0
While MyCounter < 10
' some code here
End While
VB.NET also introduces Block Scope, where a variable declared inside any structure with an End statement only exists inside that structure. For example...
VB Code:
If SomeBoolean = TRUE then
Dim MyString as String = "Some Error Message"
MessageBox.Show(MyString)
End If
In the above code, the "MyString" variable does not exist and is not visible outside of the If...End If block. This improves code readability in two ways. First, someone reading the code knows that MyString only exists inside the If...Endif block. Second, I don't have to declare MyString at the top of my procedure when it's a variable of trivial importance.
CC talks about the concept of "Live Time" - the number of lines between the first time a variable is mentioned and the last time it is used. Research shows that shorter variable live times translate into code with fewer defects - shorter live time means less opportunity for initialization errors, or for some other code to muck with the variable.
This issue is a very subjective one, and there's no one right answer. My experience has been that applying the Code Complete guidelines (and insisting that the programmers that work for me apply them) has resulted in significant and tangible improvements in the readability and quality of the code that my department produces. It also makes it easier for programmer #1 to pick up where programmer #2 left off when workloads need to be shuffled.
I think BLOCK SCOPE is a very evil construct. It makes an IF-scope declaration behave differently then a TRY/CATCH declaration.
The scope is too tight - VB is about RAD - IMHO BLOCK SCOPE and RAD don't mix. I will not allow my programmers to use BLOCK SCOPE.
And after over 25 years of maintaining and enhancing programs, peppering declarations throughout code simply doesn't work for me.
But as you said - it's a very subjective area to discuss.
Last edited by szlamany; Mar 25th, 2005 at 05:36 PM.
-
Mar 25th, 2005, 03:33 PM
#6
Re: Variable declaration and naming best practice
Boy, I can't agree with that.
I realize that there is an artistic advantage for declaring at the lowest possible scope, but consider this:
VB Code:
public Function foo() as integer
dim x as integer
x=3
do
dim x as integer
x=5
x+=1
loop while x<5
foo=x
end function
I don't know if that will compile in .NET. If it does (because the two declarations of x have different scope), then what will be returned? Actually, I have no idea what would be returned. My guess would be that the return should be 3, because the inner declaration has gone out of scope.
I can't imagine trying to maintain something like that.
I prefer to declare all variables at the top of the sub or function, treating everything within the function as being at the same scope. While this is not technically true, I find it much easier to read.
As for warting of names, that is personal preference. Some people swear by it, while others swear at it. I used to be the latter, but I have moved to a middle position.
I always wart the names of controls. I find it much easier to use intellisense if I do that, because the buttons, textboxes, checkboxes, etc., all lump together.
I generally do not wart local variables, unless I have reason to believe that the name that seems most appropriate has been used at a higher scope. To prevent that, I sometimes use an l prefix to designate a locally scoped variable.
I also try to capitalize a letter (not the first one, which I reserve for function and class names) in a variable name. This way if I type all in lowercase, I get some warning if I do not use a valid name (because the capitalization is not auto-corrected).
My usual boring signature: Nothing
 
-
Mar 25th, 2005, 03:34 PM
#7
Re: Variable declaration and naming best practice
Knew that reply would be too slow. I was referring back to DWRoelands post.
edit: Just had to correct that horrid typo.
Last edited by Shaggy Hiker; Mar 25th, 2005 at 03:57 PM.
My usual boring signature: Nothing
 
-
Mar 25th, 2005, 03:35 PM
#8
Re: Variable declaration and naming best practice
 Originally Posted by Shaggy Hiker
Boy, I can't agree with that.
I assume you are disagreeing with the same thing I just disagreed with - right?
-
Mar 25th, 2005, 03:39 PM
#9
Addicted Member
Re: Variable declaration and naming best practice
Shaggy,
I can't imagine having to maintain that, either. However if any of my programmers used a variable called "x" in production code (and then used a variable of the same name in a nested block), I'd whack them on the nose with a newspaper. 
Coding style is all about what works for the individual - or the team - that has to maintain the code. For my work, I try to follow Microsoft's best practices as much as seems reasonable (Code Complete is a Microsoft Press Best Practices publication), and my team has had a lot of success with it. That doesn't mean that someone else's guidelines or practices are wrong.
-
Mar 25th, 2005, 03:43 PM
#10
Re: Variable declaration and naming best practice
 Originally Posted by DWRoelands
However if any of my programmers used a variable called "x" in production code... I'd whack them on the nose with a newspaper. 
Get ready with that newspaper then
We have a convention here to declare i, j, k and x, y, z as Long at the top of every SUB and FUNCTION - it's in the "function" templates we copy around.
We also declare s1, s2, s3, s4 and s5 as Strings - at the top of every sub/func.
Whether we use them or not - they are always there.
We do it for RAD reasons.
These variables are for only temporary use - everyone knows that here. LOOPING - return status of a function - stuff like that.
All other variables follow the lng, str, boo prefix method. Yes we use boo - I cannot and never will type bln - but then I'm the boss, so I get my way!
-
Mar 25th, 2005, 03:53 PM
#11
Addicted Member
Re: Variable declaration and naming best practice
We have a convention here to declare i, j, k and x, y, z as Long at the top of every SUB and FUNCTION - it's in the "function" templates we copy around.
We also declare s1, s2, s3, s4 and s5 as Strings - at the top of every sub/func.
Whether we use them or not - they are always there.
Well, I can't agree with that practice - whack! 
Beta 1 of Visual Studio 2005 barks at you if you declare a variable that isn't used in the scope in which it is declared. I don't recall specifically if it prevents you from compiling, but it complains and will throw build warnings.
-
Mar 25th, 2005, 03:56 PM
#12
Re: Variable declaration and naming best practice
 Originally Posted by DWRoelands
Well, I can't agree with that practice - whack!
Beta 1 of Visual Studio 2005 barks at you if you declare a variable that isn't used in the scope in which it is declared. I don't recall specifically if it prevents you from compiling, but it complains and will throw build warnings.
Ouch!
-
Mar 25th, 2005, 04:03 PM
#13
Re: Variable declaration and naming best practice
I don't declare variables that I don't use. Also, I work alone, and have never coded with a team, which allows me to set my own style.
However, after all these years, that style is pretty well set:
When I need a For loop variable, I use x. It is not used for anything else. If I need another, I use y, then z, then I get confused and go to bed.
For strings, I use st1, st2, etc., but ONLY if they will be used very temporarily, and without a more specific purpose. Otherwise I try for a blend of easy to type, and readable variable names.
I don't wart variables. I know MS has always advocated it, and I have read plenty of articles blasting them for being inconsistent and downright crazy for doing so, but my personal view is that it comes down to ease of typing, and ease of reading. I find it hard to read warted variables (I tend to pronoune them in my mind as I read them, and warts just mean that there are many same-sounding words), so I don't use them.
My usual boring signature: Nothing
 
-
Mar 25th, 2005, 04:08 PM
#14
Re: Variable declaration and naming best practice
 Originally Posted by Shaggy Hiker
I don't declare variables that I don't use. Also, I work alone, and have never coded with a team, which allows me to set my own style.
However, after all these years, that style is pretty well set:
When I need a For loop variable, I use x. It is not used for anything else. If I need another, I use y, then z, then I get confused and go to bed.
For strings, I use st1, st2, etc., but ONLY if they will be used very temporarily, and without a more specific purpose. Otherwise I try for a blend of easy to type, and readable variable names.
I don't wart variables. I know MS has always advocated it, and I have read plenty of articles blasting them for being inconsistent and downright crazy for doing so, but my personal view is that it comes down to ease of typing, and ease of reading. I find it hard to read warted variables (I tend to pronoune them in my mind as I read them, and warts just mean that there are many same-sounding words), so I don't use them.
We seem to have very similar ideas - I just see no harm in pre-declaring my x, y and z variables.
I also won't wart (I like that term ) global variables - being global makes them obvious as to type - in my opinion!
-
Mar 25th, 2005, 04:24 PM
#15
Re: Variable declaration and naming best practice
I've seen that term in too many articles. I believe it has become the common-law name for that practice.
These days, a few extra variables makes no difference at all, it is just a few more bytes on the stack. In embedded or low memory situations (where .NET wouldn't be used anyways due to the runtime), it could still have an effect.
By the way, I was doing exactly what you are doing for a while. I would just toss in a bunch of standard variables. I stopped, but I don't remember actually having a reason. I guess I just wandered away from it. My style changes slowly over time.
My usual boring signature: Nothing
 
-
Mar 25th, 2005, 04:30 PM
#16
Re: Variable declaration and naming best practice
I mostly code by myself - although I usually have 2 or 3 high school students working here as well...
If I didn't offer them a standard boilerplate template for a SUB or FUNCTION I'd get nothing at all for consistency.
And DW - no offense, but I love this statement...
 Originally Posted by DWRoeLands
follow Microsoft's best practices
This is the same group that can't check a buffer size before loading it into memory, thus giving us the "buffer overflow injection attack of the week". I always like to point that one out
-
Mar 25th, 2005, 04:35 PM
#17
Addicted Member
Re: Variable declaration and naming best practice
This is the same group that can't check a buffer size before loading it into memory, thus giving us the "buffer overflow injection attack of the week".
Maybe not, but they can probably remember which variables they use in a given procedure and which ones they don't.
-
Mar 25th, 2005, 05:05 PM
#18
Re: Variable declaration and naming best practice
 Originally Posted by DWRoelands
Don't bet on it, I read an article savaging Hungarian Notation for being arbitrary. The authors really dug into the MS naming convention, and showed that it was not internally consistent. That sure wouldn't improve comprehension.
My usual boring signature: Nothing
 
-
Mar 25th, 2005, 05:07 PM
#19
Re: Variable declaration and naming best practice
 Originally Posted by Shaggy Hiker
Don't bet on it, I read an article savaging Hungarian Notation for being arbitrary. The authors really dug into the MS naming convention, and showed that it was not internally consistent. That sure wouldn't improve comprehension.
I'm going to draft a memo to Bill right now...
All developers must immediately store the size of the buffer in a variable called X. This must be compared to the amount of memory being transferred (stored in Y). IF X < Y THEN...call Symantec!
-
Mar 25th, 2005, 05:24 PM
#20
-
Mar 25th, 2005, 05:30 PM
#21
Re: Variable declaration and naming best practice
My own two cents. What we use here at work is a self-developed part Hungarian, part MS notation (and is in VB6). Honestly, Quite often I find that it gets in the way. It's "nice" know that when I see mobjInvoice, I know that it is a module level object that represents an invoice class. But it's overkill. What I've taken to doing in my projects at home (where it's VB.NET) is camelNotation. Variables are aptly named. counter, i, firstName. Plain, simple, and easy to read. If it's a private module variable, then it gets an underscore. _MyObjectClass So far I haven't run into any problems, although, after reading this thread, I have an idea to update my home standards. Controls current read like this FirstNameTextBox.... but I think I may how I do that.
Good read and some strong opinions here.
Tg
-
Mar 25th, 2005, 08:25 PM
#22
Hyperactive Member
Re: Variable declaration and naming best practice
 Originally Posted by DWRoelands
Beta 1 of Visual Studio 2005 barks at you if you declare a variable that isn't used in the scope in which it is declared. I don't recall specifically if it prevents you from compiling, but it complains and will throw build warnings.
You're right, it does not prevent compiling.
I use Beta 1 of Visual Studio 2005, and I like it a lot.
Of course since I'm quite new to programming I don't have many opinions yet.
Good thread, I like all the different points of view.
-
Mar 26th, 2005, 12:57 AM
#23
Re: Variable declaration and naming best practice
The standards we use at work and mine personally are almost identical to DWRoelands and I also use the _ preface for member variables like techgnome.
I'm definately not a fan of the x,i,y variable names or more so on the s1,s2,s3, but **** happens. I think all variables should be named for what they are and often use common terms like item or value or temp. Of course none of that matters because as previously stated its all about personal preference. The main thing I think to remember is that whatever you decide be consistant, it will make reading your code later or by others much easier.
Also this:
VB Code:
public Function foo() as integer
dim x as integer
x=3
do
dim x as integer
x=5
x+=1
loop while x<5
foo=x
end function
Will not compile because there is already an x declare with greater scope when the 2nd one is declared. But this would:
VB Code:
Public Function foo() As Integer
If 1 = 1 Then
Dim x As Integer = 1
End If
If 0 = 0 Then
Dim x As Integer = 0
End If
Return 0
End Function
Since the scopes do not conflict.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|