Visual Basic.Net Coding Conventions
Objects, Constants and Variables should all have an agreed naming convention applied. Programmers can then better understand the code if it has a consistent look. Following a uniform set of naming conventions when coding enhances program maintainability.
This page lists the recommended conventions when coding Visual Basic.Net projects. The conventions should be implemented wherever practical.
For applications which build on pre-existing software, it may be necessary to maintain the standards already employed in that software or restrict these standards to new modules within the project.
Variable Scope Prefix
As the project size grows, so does the value of recognising variable scope quickly. A two letter scope prefix preceding the variable name is ideal, without greatly increasing the size of variable name.
Using these conventions, it will be easy to identify the overuse of Globally scoped variables.
The Scope of a variable should be kept as small as possible. In addition to memory efficiency, there can be no interference when the variable name is used again.
For example, declare the looping variable in the "For Each" or "For Next" statements, to restrict the scope of the variable.
There is a generally accepted VB standard that Constants be declared in upper case to be easily recognised. The Constants should be prefixed with the Scope identifier.
VB.Net Compiler Options
In the Options for Visual Basic, these defaults should be set:
- Option Explicit ensures all variables are declared. It reduces the number of bugs caused by typing errors.
- Option Strict ensures code efficiency and reduces errors.
- Option Infer is only need for LINQ – it is not safe otherwise.
- Option Binary may involve more work, but is consistent with the rest of the .Net Framework.
Describing Variable Names
For the computer, a unique name serves only to differentiate one item from another. However, expressive names function as an aid to the human reader; therefore, it makes sense to provide a name that the human reader can fully comprehend.
The variable name should have mixed case and should be as long as necessary to describe completely its purpose. It should be obvious from the variable name, as to what data type (i.e. String, Boolean or Numeric) is being used. Make the variable name long enough to be meaningful but short enough to avoid being wordy.
For frequently used or long terms, standard abbreviations are recommended to help keep name lengths reasonable. In general, variable names greater than 32 characters can be difficult to read.
Minimise the use of abbreviations. Make sure that the abbreviations are consistent throughout the entire application. Randomly switching between Cnt and Count within a project can lead to unnecessary confusion. However, rather than abbreviating the word Count, be more descriptive, for example use PageCount or RecordCount.
Naming Variables – Some DON'T's
- Don't use a prefix to indicate the variable's data type – this is an old and discarded standard. Instead, make sure that the variable name is completely meaningful, and makes the data type obvious. This is much more important than using a prefix for the data type.
- Don't use a "-" prefix, this should be reserved for Events of controls and System variables.
- Don't declare variables on the same line. This does not allow descriptive comments on each variable.
- Don't use cryptic names for a variable. The names X1 and X2 are not acceptable, except to a mathematician doing complex matrix manipulation.
- Don't use "i"s and "j" for subscripts. Use meaningful names like BytePosition and RowIndex.
- Don't use abbreviations, where for a few extra characters, you can be more precise.
- Abbreviations are to be used only for long words.
- Don't use typographical marks to identify data types, such as $ for strings or % for integers.
Naming Variables – Some DO's
- Do indicate the scope of a variable with Global and Module prefixes.
- Do rename all variables, after having completed coding, until they are completely meaningful.
- Even for a short-lived variable that may appear in only a few lines of code, still use a meaningful name.
Procedure Naming Conventions
The name of the Function or Sub routine should contain mixed case characters, and should be as long as necessary to describe completely the purpose of the procedure. In other words, make the name long enough to be totally meaningful.
Naming Procedures – Some DO's
- Do use the verb-noun method for naming Functions and Sub routines, such as CalculateInvoiceTotal() or InitilizeNameArray().
- Do make the purpose of Procedure name clear, i.e. CalculateTotalSalaries, OpenCustomerDatabase, ReadCustomerRecordset.
- Do include a description of the value being returned for string Functions, such as GetCurrentClientName().
Component Naming Conventions
Each component or control used on a Windows Form should have a consistent prefix that makes the object easy to identify. The recommended Prefixes conventions for the most common component supported by VB.Net are:
cmd or btn
Directory list box
Drive list box
For controls not listed above, standardise on a unique three character prefix for consistency. Use more than three characters only if needed for clarity.
It is completely acceptable to use "obj" as a prefix for a generic Object, i.e. objTextBox or objControl or objDatabase. Unreferenced controls, like Label1, Label2, etc – need not be changed.
Prefixes for ADO.Net
As with Control Objects, a standard prefix is also required for ADO.Net (ActiveX Data Objects). Use the following prefixes to for all ADO.Net accesses.
The DataSet object should seldom be used – it is complex and inefficient. There is usually a better way of handling data by using the DataTable object.
Prefixes for Menus
Applications frequently use many menu control items, making it useful to have a unique set of naming conventions for each item controls. Menu prefixes should be extended beyond the initial "mnu" label by adding an additional prefix for each level of nesting, with the final menu caption at the end of the name string. For example the Menu File with an Open would be called mnuFileOpen.
When this naming convention is used, all members of a particular menu group are listed next to each other in VB's Properties window. In addition, the menu control names clearly document the menu items to which they are attached.
Comments are invaluable to the programmer who must maintain any intricate software. Comments in a source code listing should allow the code to stand on its own, without external documentation. The Comments must be maintained and updated in parallel with source code development.
If you write more than 20 lines without a Comment, your code is badly written!
- Separate Comments from Comment delimiters, i.e. use something like "-- ". Doing so will make the Comments stand out and easier to locate.
- Prior to deployment, remove all temporary or extraneous Comments to avoid confusion during future maintenance work.
- Use complete sentences when writing Comments. Comments should clarify the code,not add ambiguity.
- Comment as you code, because most likely there won't be time to do it later. Also, should you get a chance to revisit code you've written, that which is obvious today probably won't be obvious six weeks from now.
- When modifying code, always keep the Comments in it up to date.
The programmer needs to add error handling to each and every procedure – even where there is not the slightest possibility of an error.
There are some occasions when it is not desirable or possible to show an error message. In these cases, the Error should be returned to a higher level calling routine, by using the Err.Raise method. The Error Message returned should provide a full description of the origin of the error.
It is highly desirable that each error be logged to a central repository.
Modular programming means the breaking down of the code into "Black Boxes" using meaningful, easily comprehensible and easily debugged procedures. This helps to keep maintenance times down to minimum.
- Ideally, each procedure should be no more than 1 screen in length.
- Any code greater in length than 1 screen, should be broken into a control routine with multiple called Functions.
- Where a Method is important and critical, it should be placed in a Function, by itself, with precise handling of all error conditions.
Good Programming Practices
- Keep the lifetime of variables as short as possible when the variables represent a finite resource for which there may be contention, such as a database connection. Keep the scope of variables as small as possible to avoid confusion and to ensure maintainability. The potential for inadvertently breaking other parts of the code can be minimised if variable scope is limited.
- Be specific when declaring objects, and use the full Library Name (i.e. ADODB), instead of just the object (i.e. Recordset), to avoid the risk of name collisions. You will also have the advantage of using the IntelliSense facility.
- Use early binding techniques whenever possible. Again you will also have the advantage of using the IntelliSense facility.
- Use Select Case statements in lieu of repetitive checking of a common variable using If/Then statements.
- Explicitly release object references at the first opportunity. For example, close ADO.Net DataTable and Connection objects to insure that connections are promptly returned to the connection pool for use by other processes.
Oriented Programming (OOP)
Despite Visual Basic.Net providing Object Oriented programming features, most Visual Basic projects will have no requirement for OOP. It is recommended that, besides the use of Encapsulation for code and object Re-use, the Object Oriented features be used only when there is absolutely no other alternative.
Encapsulation is the one feature of OOP that MUST be used. There are many reasons why the technique of Encapsulation is necessary. Encapsulation makes projects easier to maintain by:
- Hiding complexity
- Reducing code to manageable procedures
- Reducing dependencies
- Reducing errors