VB.NET Coding Guidelines Comments
This is the place to view view (and add) comments related to the VB.NET Coding Guidelines.
VB.NET Coding Guidelines 3/16/2005 11:17 PM AddressOf.com
re: VB.NET Coding Guidelines 3/17/2005 10:58 PM Jeff Atwood
Do not use type characters ($, !, #, %, etc.)
My god, this is still possible? That’s so 1994.
Do not use Hungarian notation (except for private member variables).
Yeah, hungarian isn’t useful in the .NET world. And I’ve lived with code doing it both ways. It’s better without.
Do not use single-letter naming for variables.
I dunno about this. I think it’s easier to read code with terse, simple variable names for internal objects. Eg, a simple temp stringbuilder I need in a small function/sub will be named “sb”– because its use is really obvious in that small block of code. I certainly prefer that to objStringBuilder..
Coming Soon: Coding Guidelines for VB.NET 3/18/2005 11:37 AM AddressOf.com
re: VB.NET Coding Guidelines 3/18/2005 12:58 PM Sytelus
This fills few holes in standard guidelines and I was planning to write one up myself but I can’t absolutely agree with followings:
Tab indenting: I must have to be living in a cave isolated from whole world to use 2 char spacing. The default setting is 4, it looks good and thats how every other VB.Net code everywhere else in the world had ever been written since last 5 years (may be except yours). Also VS.Net, inserts spaces when you type Tab so you don’t have to worry about that.
Option Explicit/Option Strict in every file: I could never agree with this too. First of all, doing this manually instead of just once at project level is error prone. What if someone forgets, even once in a blue moon?
Select Case Else: This is what I liked in your document and I myself religiously follow it. However you might want to include in your document that not only Select Case should have Else clause but if you don’t plan to write code there, you should write a comment or throw exception:
1
2
3
4
5
6
7
8
9
Select Case i
Case 1:
....
Case 2:
....
Case Else: 'Don't forget this clause
'Code was never suppose to arrive here
throw NotImplementedException(...);
End Select
Same goes for If-Then: there always should be If-Then-Else.
1
2
3
4
5
6
If money > 1000 Then
GoAndSpend()
Else
'Just write comment why there is no
'code in Else clause
End If
re: VB.NET Coding Guidelines 3/18/2005 1:38 PM Cory Smith
Sytelus, thanks for the comments. To respond to a couple of them:
Tab & indenting: The reason I use 2 spaces is that, to me, it’s just a readable as 3 or 4. I believe the VB runtime team uses 3 spaces and the default in the IDE is 4 (as you suggest). However, if your code as a lot of indentation (which VB.NET does), you quickly end up with some pretty long lines and a lot of extraneous white space. The reason I settled on 2 spaces is because of these issues and it looks great when publishing code one the web and in print. And before this issue get’s out of hand like the comments on Brad’s C# version… In the end this is a really minor guideline. Use whatever your comfortable with since, with the “pretty print” feature in the IDE, you can quickly set the spacing to your preference.
Option Strict/Explicit in every file. Although there is an option in the IDE to enable this, the problem is that when you share code with others. The default in the IDE is these turn off. So when you provide code and they incorporate it within their project, the compiler features enabled when these are turn on are not gained. Also, if they are in every file, you know, without a doubt, what the options are set to. Finally, if you turn the options on in the IDE and you get code from another source, your going to see a potentially see a ton of errors. Have to fix them before (or adding Options Off) even being able to if the code does what you are looking for it to do. One final point. During code reviews, you can see this in the source… again, absolutely no questions being raised.
Select Case Else. Very good suggestion and your not the first to bring it up (I’ve had a similar conversation with another individual). I’m really not sure how to approach this one. Not wanting to get into a situation where these guidelines become too restrictive. Personally, in my code, I avoid ever having an empty Case Else. I think there should always be a default setting and I make this one inside of the Case Else. If there is a case when there is no default, then I raise an error. As for If/Then Else sections being empty, I just don’t have them.
re: VB.NET Coding Guidelines 3/18/2005 1:49 PM Cory Smith
Jeff, to comment on the single letter variables, this guideline reflects what’s in the Design Guidelines for Class Library Developers.
However, sometimes it makes perfect sense and is, in the end, very understandable to use shorter variable names. This is something that you have to consider in the context of the code being written.
For example… rather than have mouseX or screenX or pictureX, I’ll probably just use x. If the method being created is very small (less than 10 lines or so), I’ll use fs for FileStream. As the method grows in size, that’s where things can get confusing when using shorter, non-descript variable names. Going back to my x variable, instead of using mx, sx and px if I’m referencing multiple x variables, I’ll then use the the more descriptive counterparts. This is more of a general guideline and really depends on the context of the variables being used. In the end, my general rule is to use variables that someone else can understand and would require little to no explanation.
VB Coding Code Guildlines 3/18/2005 2:21 PM Brad McCabe’s WebLog
VB Coding Code Guildlines 3/18/2005 2:22 PM Brad McCabe’s WebLog
VB.NET Coding Guidelines 3/18/2005 Banging My Head Against The Wall
VB.NET Coding Guidelines 3/18/2005 4:28 PM AddressOf.com
re: VB.NET Coding Guidelines 3/18/2005 11:19 PM Bill McCarthy
Some alternative POV’s:
2.1 Tab spacing. 3 is a lot clearer, and less likely to be be a mistake. 4 is excessive, 2 is too small.
2.3 block formatting. Do NOT include Case Else unless you are explicitly intending to hanlde all other cases. Case Else implies that other cases have already been considered, whereas this is oftne not the actual “case”.
2.8 Naming. Use of single letter varaibles is okay for simple iterators eg: For i As Int32 = 0 to foo.Length -1
2.9.1 contradicts the last point of 2.11
2.10 Consider grouping member by fucntionality rather than accessibility. Interfaces should be nested inside regions
2.11 Do NOT use Modules unless you want all memebers to be accessible without using the type name. Modules should be used sparingly.
2.13 Collections should only be used if yu want to have public Add/Remove methods, otherwise use/return arrays.
Do NOT use events rather than overriding if your class is not sealed or the event is public to other components/classes. The order of events fire is not guaranteed.
Additional comments.
-
Consider removing all project wide Namespace imports and isntead explicitly state them on the top of each code file.
-
Consider using aliases for Imports to make code easier and improve readability, eg:
1
2
Imports VB = Microsoft.VisualBasic
Imports WinForms = System.Windows.Forms
-
when overriding a method always include a call to the base class method. If the base class method is not called, then comment out the call (do not remove it) and incldue a comment explaining.
-
Do consider using optional parameters rather than many overloads. When using optional parameters, have the default As Nothing.
-
Prefer object methods to language constructs where appropiate: eg: myString.Length instead of Len(myString)
If you use the language constructs include a note such as:
1
myLength = Len(myString) 'using Len in case myString is Nothing
2.4 Single line statments. For Select Case statments these should really be avoided, as readability of a multiple Case is less clear, EG:
1
2
Select Case foo
Case 1, 2, 3 :x = y
That is BAD.
2.6 Spacing. Consider using multiple new lines (2+) to seperate types, and two lines between methods. Use single line spacing inside methods.
re: VB.NET Coding Guidelines 3/19/2005 8:22 PM Richard Tallent
Some alternative points (I, unfortunatelty, disagreed with most of this post, though I appreciate hearing all sides).
-
4-space tabbing looks great and it highly readable. Further, I HATE editors that convert tabs into spaces–makes it harder to navigate the code by keyboard. Leave them as tabs so everyone can have their personal choice of tab stops.
-
If…Then on a single line is highly readable, povided it’s a single Then statement and no Else clause.
-
I prefer to indent my blocks almost C-style, probably because of my background in C. Example:
1
2
3
Public Sub foo()
' Do some stuff
End Sub
-
I avoid Option Strict. It has never bought me anything and has only made my code less readable. But I’ve been programming in languages with implicit conversion (which, granted, is a subset of Option Strict Off allows) for most of my life. Agree wholeheartedly on Option Explicit.
-
Since I don’t use the VS IDE, I like to line up similar consecutive code using tabs–probably a bad habit from my COBOL days. Example:
1
2
Dim MyFirstName As New String = "Richard"
Dim MyLastName As New String = "Tallent"
-
Initialization upon instantiation of new variables is great, but it should be avoided avoided inside loops so the variable is re-initialized on each iteration.
-
Single-letter variables are fine to me if their function is clear.
-
You didn’t cover With…End With, a tool that should be part of every VB.NET programmer’s regular vocabulary. In fact, judicious use of with can avoid naming a variable at all. In the caveats, it shouldn’t be nested (works fine, but confusing).
-
No coverage of when to use For Each…Next vs. For…Next. More of a optimization thing, but affects readability.
re: VB.NET Coding Guidelines 3/20/2005 1:22 AM Har
That was exelent. i needed those. thanks
re: VB.NET Coding Guidelines 3/20/2005 8:54 AM Rik Hemsley
I explicitly specify the type of a new object when I want to force myself to work with the interface of a base class, or the Interface implemented by a class. This makes it easier to switch implementations in future.
1
Dim Formatter As IFormatter = New PrettyFormatter()
I’m against coding ‘standards’ in general. Everyone has their own taste. My own style is similar to that described in this article, but when editing, or adding to, code written by others, I follow their style. I believe ‘be polite’ is the only necessary axiom.
Rik
re: VB.NET Coding Guidelines 3/20/2005 9:37 AM Leigh Kendall
Great reference…
One thing I didn’t see addressed however, in the spacing section is spacing in Function/Sub declarations and property declarations. For example, I always put an empty line after my function/sub header and one before the End Function/Sub.
Example:
1
2
3
4
5
Public Function FunctionName() as String
<code here>
End Function
Property declarations I usually don’t, since the Get/Set sort of breaks it up.
Can you address that? Perhaps this really is personal preference, but it drives me nuts when I see functions all squashed together without any logical whitespace anywhere.
re: VB.NET Coding Guidelines 3/20/2005 11:58 PM vijay…jvijay_19@yahoo.com
hi, i am vijay .i need a help. i dont know where to post.anyway coming to matter.my task was to get the input data from FileName.XSL MS.EXCEL and Format the data and to present in other .XSL .can u post ur guidelines to my EMAIL ID…jvijay_19@yahoo.com..plzzzzzzzzzz
thanking u,
with regards, vijay
re: VB.NET Coding Guidelines 3/21/2005 12:45 AM Cory Smith
A couple of people have mentioned that I didn’t make a reference to With/End With.
This was on purpose. First, right now, I don’t use them. Why? Well, because they hinder my debugging activities. You can’t get the variables value in debug mode. When (and if) this is corrected, I would probably use them. It does help read’ability, but without debug’ability I find it pretty much useless.
To be fair, I should mention that there is a slight performance gain using With/End With in some specific circumstances. When you have a With referencing a variable that will be boxed/unboxed, then a hidden variable reference is created and used in the CIL. However, if this is not the case, the CIL is exactly the same as if you didn’t use With/End With. Even then, the performance gain you get may be minimal depending on what your doing.
re: VB.NET Coding Guidelines 3/21/2005 4:14 AM John Barone
Just a few thoughts:
-
I’m one of (seemingly) the few that prefer two-space tabs. To me, there is enough space to see that there is an indent, and it doesn’t eat too much of the line.
-
Nothing was said about Word Wrap. I personally like it, even though it has its disadvantages. Why? Because I work w/both a laptop and a desktop, which have different resolutions, etc. I find that just not worrying about where to place line continuation characters saves time to do more important stuff…
As an aside, I have code in VB6 that I wrote years ago on a 800x600 monitor which have continuation characters scrupulously placed to make things look pretty, etc. Now it just looks dumb. With word wrap, I don’t have to worry about it…
- I’m one of those who prefer to use overrides instead of events whenever possible. Why: 3a. Like a previous person said, there is the issue of when the code gets to run. With an event, you have to just accept that you will get called, but not in a particular order. But, with an override, you can move yourself to the back of the line or the front of the line, depending on need.
3b. Performance: My understanding (from a Devscovery presentation last year) is that the override is much faster than doing the same thing via an event, since you aren’t messing with delegates, etc.
3c. Clean OOP: In what other situations (other than UI/forms), do you write yourself events, and then handle them in child classes instead of simply just overriding a method?
I suspect that this is in place b/c most VB people are naturally more comfortable using Events rather than overrides b/c that’s how forms were interacted with in previous versions.
-
I’m also probably one of the few that likes to just use the underscore only (sans the “m”) to denote class-level variables. I.E., _something instead of m_something. I know this one has some issues; it’s just that m_something starts making me think in Hungarian…
-
Regions: I like the “Accessiblity” guideline, and generally use it, but loosely. I do try to put interfaces implementations in their own regions whenever possible. I sometimes also like to place related code together regardless of accessiblity level.
Also, I like to put all items relating to that property together.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
' Example; this is aircode
#Region " Whatever Property "
Private _whatever As String
Public Property Whatever() As String
Get
Return _whatever
End Get
Set(Value As String)
_whatever = Value
End Set
End Property
' For now, assume a WinForm property
Public Function ShouldSerializeWhatever as Boolean
' code
End Function
Public Sub ResetWhatever
' code
End Sub
#End Region
re: VB.NET Coding Guidelines 3/21/2005 9:20 PM eric
Just wondering the justification of this …
“Do use the Visual Basic runtime methods rather than .NET Framework where appropriate. “
Aren’t the VB Runtime methods just a long way down the call stack to their .net framework counterparts? It’s my understanding that functions like “Right()” just call the “String.SubString” anyway.
Why travel all the way down the functions underlying call stack to get to the vb runtime calls?
re: VB.NET Coding Guidelines 3/25/2005 3:28 PM
Nice. How about a nice, small ascii text version to take home. :)
re: VB.NET Coding Guidelines 3/25/2005 5:07 PM Cory Smith
Eric,
To answer your question about the justification, I guess I can answer the question in three parts.
First, taking the example of Right(); yes, in the end, it will call upon String.Substring(). It’s doing a bit more than that, which in many cases helps to make sure you code is more stable. Here is basically what the code looks like.
1
2
3
4
5
6
7
8
9
10
11
12
13
Public Shared Function Right(ByVal value As String, ByVal length As Integer) As String
If (length < 0) Then
Throw New ArgumentException("Length is too short.")
End If
If (length = 0 OrElse value Is Nothing) Then
Return ""
End If
Dim size As Integer = value.Length
If (length >= size) Then
Return value
End If
Return value.Substring(size - length, length)
End Function
By using Right, you don’t have to worry about whether or not the value is nothing or even if the size you want is within the range. However, if this is important to you, then by all means, use Substring directly. I added the “where appropriate” because I think there are some areas where it makes more sense to use the objects (String for example) method over the runtime method. The main point here is to not be afraid to utilize these methods and if you don’t use them, be sure you are aware of the reason as to why you aren’t.
The second reason is that this suggestion is shared by members of the VB team; obviously they worked hard to make these available in order to make our development lifes more productive and I don’t blame them for wanting to see the fruits of their labor leveraged by us. In addition, I’m constantly seeing false information being spread regarding the “non-use” of the runtime and how it’s not the “.NET” way. These are every bit a part of the .NET Framework as say Windows Forms, ADO.NET, ASP.NET, etc. and should be given as much, if not more, consideration in being leveraged, especially by VB.NET developers.
Third, the compiler is able to optimize the code when you leverage several of these and my guess is this will improve over time. Not using these puts that responsibility on you, the developer and you don’t gain any of these benefits in the current and future compiler. This is a minor point, but one I feel I should mention for completeness.
In the end, use whatever you are most comfortable with. Just be aware that it’s not “wrong” to leverage the runtime, in fact, in many cases its significantly better than trying to do the same task on your own. To be fair, there are some areas in the VB runtime that don’t perform that well; in those instances, you have to decide whether performance is your key concern and if it is, for those instances (and, this part is key, if it truely is a bottleneck), find an alternate solution. Performance is a completely different subject and there is no one right answer.
re: VB.NET Coding Guidelines 3/25/2005 5:11 PM Cory Smith
John,
The use of the underscore alone has problems in certain circumstances with the compiler. I’m don’t remember what the instance that I ran into the past was, but I will tell you it can bite you in the rear when you least expect it. I was originally a proponent for using the underscore alone and was told about this issue and said “well, I haven’t run into it”. When I did, it caused me to switch. Also, the VB runtime team uses m_, so if they are doing it, I suppose its good enough for me.
re: VB.NET Coding Guidelines 3/26/2005 2:33 AM Tom
I’m glad to see something started on this subject and agree with much of what has been stated.
I would echo the comments by Richard Tallent. I code similarly and my only background is classic asp with vbscript. However, I hand code everything.
I would also add that comments should never be placed at the end of a line, but always preceding the code, preferably followed immediately with an underline to make it stand out.
For example:
1
2
3
'my comment goes here
'---------------------
This is my code.....
Comments should line up with respective code indentation and for indentation, ALWAYS use 4 spaces, no exceptions.
Every page of code should also have a revision history and statement of purpose.
Subs and functions should be highlighted with cmmentd lines such as this example from the portal starter kit:
1
2
3
4
5
6
7
8
9
10
11
12
'*******************************************************
'
' GetThreadMessages Method
'
' Returns details for all of the messages the thread, as identified by the Parent id string.
'
' Other relevant sources:
' + <a href="GetThreadMessages.htm" style="color:green">GetThreadMessages Stored Procedure</a>
'
'*******************************************************
Public Function GetThreadMessages(ByVal parent As String) As SqlDataReader
VB.NET Coding Guidelines 3/26/2005 2:55 PM Gianluca’s Blog
Coding Style Guidelines for VB and C# 3/26/2005 10:18 PM Rob Windsor’s Weblog
Coding Style Guidelines for VB and C# 3/26/2005 11:34 PM Rob Windsor’s Weblog
re: VB.NET Coding Guidelines 3/28/2005 10:21 AM Schneider
2.11 Do not create a Class containing only Shared methods. Use Modules instead.
Can some explain this?, seems you open yourself to more problems here. Global variables, and other crazy things you could do.
Why not make the class constructor protected/friend and non inheritable.
Beside I have not seen a case where I needed a .bas module. I think they are an annoying temptation for difficult design problems.
2.8 Naming Do use the m_ prefix for private Class level member variables. this guideline is extended to all private member variables.
Are you saying we should name private variables in a method with the prefix of “m_”?
If that’s the case I disagree. I want a obvious way the differentiate between class scope private variables and the local scope variables with-in a method.
If the variable is used and declared in a method I do not add a prefix, The block scope and lack of prefix tells me it method variable. All though I have considered a different prefix but just for obfuscation purposes.
Schneider
re: VB.NET Coding Guidelines 3/28/2005 11:34 AM Cory Smith
“private Class level member variables”…
I don’t mean in the methods, the private member variables that are usually used to house internal class level information, such as variables behind properties and other state information. For example:
1
2
3
4
5
6
7
8
9
Class Test
Private m_something As Integer
Public Sub Whatever()
Dim hmmm As Integer
End Sub
End Class
VB.NET Coding Guidelines by Cory Smith 3/29/2005 12:56 AM Alex’s BLogs
re: VB.NET Coding Guidelines 3/30/2005 3:01 AM Tim Ensor
One thing that annoys me with attributes on the previous line with a continuation is how they work with outlining. If I have
1
2
3
<serializable> _
Public Class Foo
...
When I collapse that I see
1
<serializable> _...
Which doesnt tell me what the class is.
Unfortunatley I find that more readable than the alternative:
1
2
<serializable> Public Class Foo
...
Which is fine in that case, but if you have lots of attributes, it becomes very cluttered.
re: VB.NET Coding Guidelines 4/4/2005 3:23 AM amit
i want to coding in vb.net
re: VB.NET Coding Guidelines 4/5/2005 4:15 AM manoj
In visual basic.Net i want develop project but i dont have project
re: VB.NET Coding Guidelines 4/12/2005 2:51 AM dawood
1
2
3
4
5
6
7
8
<Flags()> _
Public Enum ExitWindowFlags
LogOff = &H0
Shutdown = &H1
Reboot = &H2
Force = &H4
PowerOff = &H8
ForceIfHun
re: VB.NET Coding Guidelines 5/3/2005 1:36 PM Schalld
I still feel that hungarian notation has an important place. Especially when talking controls and variables. It makes life so much easier when doing a code review to have them named correctly.
re: VB.NET Coding Guidelines 5/17/2005 4:57 PM NeoRev
Another good suggestion is to remove the Imports statement from the project properties. This way it forces you to do things the .NET way rather than rely on the legacy VB6 style functions. Not only does it improve your code quality, it can improve performance and portability.