Results 1 to 23 of 23

Thread: Variable declaration and naming best practice

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2005
    Location
    Huddersfield, England
    Posts
    83

    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?

  2. #2
    New Member
    Join Date
    Mar 2005
    Posts
    9

    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.

  3. #3
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    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.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  4. #4
    Addicted Member
    Join Date
    Mar 2005
    Posts
    142

    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:
    1. Dim MyCounter as Int32 = 0
    2. While MyCounter < 10
    3. ' some code here
    4. 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:
    1. If SomeBoolean = TRUE then
    2.    Dim MyString as String = "Some Error Message"
    3.    MessageBox.Show(MyString)
    4. 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.

  5. #5
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Variable declaration and naming best practice

    Quote 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:
    1. Dim MyCounter as Int32 = 0
    2. While MyCounter < 10
    3. ' some code here
    4. 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:
    1. If SomeBoolean = TRUE then
    2.    Dim MyString as String = "Some Error Message"
    3.    MessageBox.Show(MyString)
    4. 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.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    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:
    1. public Function foo() as integer
    2.   dim x as integer
    3.  
    4.   x=3
    5.   do
    6.     dim x as integer
    7.     x=5
    8.     x+=1
    9.   loop while x<5
    10.  
    11.   foo=x
    12. 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

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    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

  8. #8
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Variable declaration and naming best practice

    Quote 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?

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  9. #9
    Addicted Member
    Join Date
    Mar 2005
    Posts
    142

    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.

  10. #10
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Variable declaration and naming best practice

    Quote 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!

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  11. #11
    Addicted Member
    Join Date
    Mar 2005
    Posts
    142

    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.

  12. #12
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Variable declaration and naming best practice

    Quote 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!

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    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

  14. #14
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Variable declaration and naming best practice

    Quote 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!

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  15. #15
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    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

  16. #16
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    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...

    Quote 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

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  17. #17
    Addicted Member
    Join Date
    Mar 2005
    Posts
    142

    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.

  18. #18
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Variable declaration and naming best practice

    Quote Originally Posted by DWRoelands
    Maybe not, but they can probably remember which variables they use in a given procedure and which ones they don't.
    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

  19. #19
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Variable declaration and naming best practice

    Quote 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!

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  20. #20
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Variable declaration and naming best practice

    Yeah, you do that.

    However, don't expect a reply, they only speak in acronyms over there.
    My usual boring signature: Nothing

  21. #21
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    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
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  22. #22
    Hyperactive Member
    Join Date
    Mar 2005
    Location
    Maine, USA
    Posts
    277

    Re: Variable declaration and naming best practice

    Quote 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.

  23. #23
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339

    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:
    1. public Function foo() as integer
    2.   dim x as integer
    3.  
    4.   x=3
    5.   do
    6.     dim x as integer
    7.     x=5
    8.     x+=1
    9.   loop while x<5
    10.  
    11.   foo=x
    12. 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:
    1. Public Function foo() As Integer
    2.         If 1 = 1 Then
    3.             Dim x As Integer = 1
    4.         End If
    5.  
    6.         If 0 = 0 Then
    7.             Dim x As Integer = 0
    8.         End If
    9.  
    10.         Return 0
    11.     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
  •  



Click Here to Expand Forum to Full Width