Skip to content

Planet-Source-Code/sean-street-standards-for-visual-basic__1-37882

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

Standards for Visual Basic

Description

This article provides, in detail, the recommended standards as directed by Microsoft for developing and maintaining Visual Basic applications. I was surprised to find that this kind of information was hard to come by, and that many professional developers were not aware that a compiled list even existed. So, I share this knowledge with you, to instill along your developmental travels. I'm sure there are some areas that are rather vague, so, by all means, please feel free to comment, make suggestions or recommend publications as you see fit.

More Info

Submitted On 2002-08-12 15:22:30
By Sean Street
Level Beginner
User Rating 4.7 (109 globes from 23 users)
Compatibility VB 4.0 (16-bit), VB 5.0, VB 6.0, ASP (Active Server Pages) , VBA MS Access
Category Coding Standards
World Visual Basic
Archive File Standards_1172588122002.zip

Source Code


Standards for developing and maintaining Visual Basic applications


Design

Designing Modules and Procedures
  • Every procedure should perform a specific function.
  • Try to make procedures as self-contained (loosely coupled) as possible.
  • Put complex processes in specialized like mathematical equations procedures.
  • Put data input/output operations in specialized procedures in case the methods of handling data I/O is changed later.
  • Alphabetize procedures within a given module. It is much easier to find a particular procedure when they are sorted.
  • Use descriptive names for procedures and modules. Descriptive names allow developers to better understand what the procedure is doing.
    • To save keystrokes, begin to type the procedure/module name then press CTRL-Space to have Visual Basic complete the name.
    • Use mixed-case letters when naming procedures and modules.
    • Avoid abbreviating names when possible.
  • Give procedures single exit points. Use a common label (ex. ExitHandler) to exit a procedure. Try to only use the Exit Sub/Exit Function in the exit label of the procedure.
  • Always explicitly define the scope of a procedure.
  • Try to use parameters to pass data between procedures instead of using global and module level variables.
  • Specify a data type for each arguments of a procedure.
  • Always preface arguments with ByVal and ByRef.
    Note: Microsoft recommends prefacing only ByVal arguments. I suggest prefacing all arguments. The arguments will line-up nicely when carrying over to the next line and it will make migration to .Net easier. Whichever you choose, make sure it's consistent throughout all your development team's applications.
  • Validate passed arguments before using them.
  • If an argument accepts only a small set of values, use enumerations (Enum).

Creating Objects and Modules
  • Always use Option Explicit in all modules.
  • Try to use a common set of global constants in objects so they will be understood by all members of the development team and can be easily changed.
  • Never hard-code paths, application names and version numbers in objects as these have a tendency to change frequently.
  • Try to use Property procedures rather than global/public variables to access data from objects. This allows you to perform data validation when values are read or changed.

Conventions

Hungarian Notation
  • Use Hungarian Notation. -Period-   Below is a list of the naming conventions as recommended per Microsoft.


    • Prefixes for variable data types:

    • Data Type Prefix Example
      Array a astrEmployeeNames
      Byte byt bytRow
      Boolean bln blnSaveChanges
      Currency cur curSalary
      Date/Time dtm dtmStartTime
      Double dbl dblTotalDue
      Long lng lngUserId
      Integer int intQuanity
      Single sng sngTax
      String str strUserName
      Variant vnt vntCheckSum

    • Prefixes for variable scope:

    • Scope Prefix Example
      Global g gstrFilePath
      Module/Form m mblnIsDirty
      Static s sblnHasRunBefore
      Procedure (no prefix) lngReturnValue

    • Prefixes for common controls:

    • Control Prefix Example
      Check box chk chkActive
      Class C CEmployee
      Class object(instantiated) cls clsEmployee
      Combo box cbo cboLanguages
      Command button cmd cmdCancel
      Common dialog dlg dlgOpenFile
      Communications com comFax
      Data control dat datEmployees
      Dictionary dic dicEmployees
      Dictionary list box dir dirSource
      Drive list box drv drvTarget
      File list box fil filSource
      Form frm frmMain
      Frame fra fraOptions
      Graph gra graStatus
      Grid grd grdInventory
      Group push button gpb gpbChannel
      Horizontal scroll bar hsb hsbVolume
      Image img imgDisplay
      Label lbl lblStatus
      Line lin linVertical
      List box lst lstEmployees
      List view lvw lvwFiles
      MAPI message mpm mpmSentMessage
      MAPI session mps mpsSession
      MDI child form mdi mdiEmployeeData
      Menu mnu mnuSave
      OLE container ole oleWorksheet
      Option button opt optEnglish
      Outline out outOrgChart
      Panel pnl pnlSettings
      Picture box pic picLogo
      Picture clip clp clpToolbar
      Report rpt rptQtrlEarnings
      Shape shp shpCircle
      Spin spn spnPages
      Status bar stb stbStatus
      Text box txt txtFirstName
      Timer tmr tmrAlarm
      Tree view tvw tvwFolders
      Vertical scroll bar vbs vbsRate

    • Prefixes for database objects:

    • Object Prefix Example
      Database db dbCustomers
      Field fld fldFirstName
      Index idx idxEmployeeId
      Query/QueryDef qry qryEmployees_s_All
      Recordset rst rstEmployees
      Table/TableDef tbl tblEmployees

    • Prefixes for arguments, enumerations, and user-defined types:

    • Item Prefix Example
      ByRef r rblnSuccessful
      ByVal v vlngEmployeeId
      Enum enu enuBorderStyle
      User-defined type udt udtEmployee

Naming Conventions
  • Microsoft recommends naming constants with the c_ prefix as in c_MaximumCountAllowed. The former standard of using all caps as in MAXIMUM_COUNT_ALLOWED is antiquated. I personally still prefer the all-caps method to the suggested one and it is the one we still use on my development team. In the end, whichever method you choose, make sure it's consistent throughout all your development team's applications.
  • Microsoft recommends prefacing the members of an enumeration with a three to four character prefix that indicates the company or application. For example, Visual Basic's enumerators use the prefix vb as in vbModal and vbYesNoCancel. You could also use an abbreviation of the company as in cssVisualBasic.

Variables, Constants and Enumerations

Using Variables, Constants and Enumerations
  • Never hardcode numbers when enumerations are available. For example, use MsgBox "Continue", vbYesNo instead of MsgBox "Continue", 4.
  • Use system constants whenever enumerations are not available. For example, use Me.WindowState = vbMaximized instead of Me.WindowState = 2 . You can check to see if a constant is available by highlighting the word and pressing F1.
  • Use constants to refer to elements of a control array.

    Here's a neat trick concerning control arrays that was taught to me that I'll pass along.
    Let's say you name all of the buttons on a form cmdEmployeeButtons. Then, when you want to reference them in code, all you have to do is call the cmd property. The enums will popup, and all you have to do is select the appropriate enum. If you add a button later on, just add its associated index to the enum.


    Private Enum enuCommandButton
        cssPrintLetterBTN = 0
        cssCloseBTN = 1
    End Enum


    Private Sub Form_Load()
        cmd(cssPrintLetterBTN).Enabled = False
    End Sub


    Private Property Get cmd(ByVal vcssCommandButton As enuCommandButton) As CommandButton
        Set cmd = cmdEmployeeButtons(vcssCommandButton)
    End Property

  • Give variables descriptive names; avoid naming variables Temp.
  • Abbreviate only frequently used or extremely long names.
  • Use the positive form in Boolean variables. For example, use blnLoaded instead of blnNotLoaded.
  • Try to avoid using the Variant data type.
  • Use an ampersand (&) to concatenate strings instead of the addition (+) symbol.
  • Minimize the scope of the variable to the least common denominator.

Error Handling

Using the Err object and On Error commands
  • Include error handling in every procedure in your application regardless of size or purpose.
  • Use On Error GoTo to trap unexpected errors.
  • Use On Error Resume Next to trap expected errors.
  • Create consistent error handler blocks.
  • Use caution when using Resume as the risk of an infinite loop arises.

Formatting Code

Using Line Breaks and the Continuation Character
  • Never place multiple statements on a single line. For example:

    Incorrect:
    Print "Hello": Print "Good-Bye"

    Correct:
    Print "Hello"
    Print "Good-Bye"


  • Do not exceed 90 characters on a single line. The reason is at least two fold, first at a resolution of 800 X 600 and at a normal font, 90 characters fit nicely on a single line. The second reason is when the module is printed, 90 characters, again, fit nicely on a single line. So, even if you have your resolution set at 1024 X 768, break the line at 90 characters.
  • Use the continuation character. For Example:
    I've grayed out the code and enlarged the continuation characters so they standout a bit more.


    Public Sub ShowContinuationExample(ByVal vstrMessageToDisplay As String, _
                                       ByVal vstrDialogTitle As String)

    Const PROCEDURE_NAME As String = "ShowContinuationExample"
    Const DISCLAIMER As String = "This comment is the opinion of the user and not " & _
                                 "necessarily the opinion of this establishment."

    On Error GoTo ErrorHandler

          '---Display the message provided and add our custom comment.
       MsgBox vstrMessageToDisplay & vbNewLine & DISCLAIMER, _
              vbOKOnly And vbInformation, _
              vstrDialogTitle

    ExitHandler:
       Exit Sub

    ErrorHandler:
       Select Case Err.Number

          Case Else   '---Handle unexpected VB errors.

             Err.Raise Err.Number, _
                       Err.Source & vbNewLine & Space(4) & Me.Name & "." & PROCEDURE_NAME, _
                       Err.Description

       End Select

       Resume ExitHandler
       Resume   '---Used for debugging purposes.
    End Sub

  • Break complicated expression evaluations. For example:

    Incorrect:
    If blnMoving And sgnSalary = (sngMonthlyPayments * MONTHS_PER_YEAR) And _
          Salary = (sngHourly * HOURS_PER_YEAR) Then

    Correct:
    If blnMoving _
          And sgnSalary = (sngMonthlyPayments * MONTHS_PER_YEAR) _
          And Salary = (sngHourly * HOURS_PER_YEAR) Then


Using Indentation
  • Indent continuation lines. Notice how the arguments line up in the ShowContinuationExample procedure example above.
  • The accepted number of characters per tab stop is 3. This is the standard as directed by Microsoft, although VB defaults to 4. Using anything less than 3 characters reduces the visual definition. Anything more wastes too much space, especially in complicated code.
  • Indent after an If statement when carried to the next line (when End If is used).
  • Indent after an Else statement.
  • Indent after a Case statement.
  • Indent after a Do statement.
  • Indent after an Edit or AddNew method call of a recordset.
  • Indent after a BeginTrans call.
  • Indent the bodies of all user-defined data type and enumeration declarations.

Using White Space and Blank Lines
  • Insert a blank line before and after each If...Then construct.
  • Insert a blank line before and after each Select Case construct.
  • Insert a blank line before and after each For, Do and While loop.
  • Insert a blank line after declaring a block of variables.
  • Insert a blank line between groups of statements that perform unified tasks.
  • Insert two blank lines between procedures.

Commenting Code

General Practices
  • Document the purpose of the code (why not how).
  • If you need to deviate from good programming style, explain why.
  • If an error is anticipated, then document when and why. For example: If a user selects Cancel on a ShowOpen common dialog box and the RaiseError option is selected, a known error is raised.
  • Use descriptive headers before each procedure detailing useful information. For Example:


    '-----------------------------------------------------------------------------------------
    ' Author      Sean Street - sls
    ' Date        08/12/02
    ' Purpose     Explain what the procedure does; not how it's used.
    ' Notes       Explain any special notes.
    ' Input       Explain, if applicable, any arguments.
    ' Output      Explain, if applicable, any outputs generated.
    ' Called By   This section should always be filled. Who is calling this procedure?
    ' Revisions   Detail any changes to the procedure since its conception.
    '-----------------------------------------------------------------------------------------
    Public Sub ShowContinuationExample(ByVal vstrMessageToDisplay As String, _
                                       ByVal vstrDialogTitle As String)
            .
            .
            .


Make Comments Readable
  • Only use solid-character comment lines for major comments.
  • Use an apostrophe instead of the REM keyword to denote comments.
  • Use complete sentences instead of sentence fragments.
  • Avoid using abbreviations.
  • Capitalize words to indicate their importance.

Document Code Processes
  • Comment the line before every If statement.
  • Place a comment before every Select Case statement.
  • Comment the line before every For, Do and While loop.
  • Place a comment before every statement that changes the value of a global variable.
  • Comment any complicated code segments that other developers may find confusing.

User Interaction

Interface design
  • Assign the proper border style to every form.
    • Fixed Dialog - This is probably the most common border style for forms. With fixed dialog forms, you can have a title bar and a control-menu box, however the Minimize and Maximize buttons are not displayed.
    • None - This is probably the least common border style for forms. Forms with the None border style do not have title bars nor have any control-menu buttons. There are very few cases when this style should be used (Splash forms are good exception).
    • Fixed Single - This style closely resembles that of the Fixed Dialog. The main difference is that you can display the Minimize and Maximize buttons. A Fixed Single, like the Fixed Dialog cannot have its size adjusted.
    • Sizable - When using Sizable forms its contents should resize accordingly. If the contents do not resize with the form, try using a Fixed Dialog or Fixed Single style instead.
    • Fixed/Sizable ToolWindow - This style allows you to float forms over main windows of a program. Forms of these types are usually reserved to host tools or actions that can be applied to the main window.
  • Give every form an intelligent and consistent startup position.
  • Correctly unload forms and free the resources that they consume. This is a big issue. When a form is unloaded its resources remain in memory. For example, you can still access procedures from a form that has been unloaded. To fully unload the form, set it equal to nothing:

    Set frmEmployees = Nothing

  • Do not allow forms to morph. This includes hiding buttons, menu items, textboxes, etc. Instead, set the Enabled property to false. This also includes changing the colors, fonts, and sizes.
  • Assign textboxes, combo boxes and other "single-lined" controls the same height as a standard combo box. Ironically, Visual Basic defaults textbox controls to 495 twips, however, the standard is 315 twips.
  • Place labels at the proper vertical location in relation to the controls with which they coincide.
    • Set the Autosize property to True, unless there's a good reason to do otherwise.
    • Set each label's BackStyle property to Transparent, unless there's a good reason to do otherwise.
    • Set the Top property to 60 twips greater than the Top property of its related control.
    • End label captions with a colon (:).
  • Avoid using the Tag property when possible.
  • Use option buttons to display static lists of five or fewer items.
  • Use a list box for static items over five or to display dynamic lists.
  • You can also use a combo box for static items over five or to display dynamic lists when space is a concern.
  • Use checkboxes to let users toggle options in small static lists.
  • Avoid using the Picture Box control unless absolutely necessary.
  • Format, organize and display menus consistent with Windows application.
  • Assign shortcut keys to frequently used menu items. Reserve common Windows shortcut keys for their respective function. For Example: F1 indicates Help.
  • Every toolbar button should have a corresponding menu item.
  • Use system colors opposed to custom colors whenever possible.

User Input and Notification
  • Set the tab order property of all the controls on your form so they are intuitive.
  • Create a default command button and default cancel button by using the Default and Cancel properties when feasible. If using a multiline textbox, however, you're better off not designating a default button because pressing the Enter key will result as a clicking of the default button instead of the next line of the multilined textbox.
  • Assign access keys to commonly used command buttons by using the ampersand & character.
  • Set the MaxLength property of textboxes that store data into fixed length fields of a database.
  • Provide pop-up menus whenever possible.
  • Use the mouse pointer to provide feedback to the user. For example: Use an hourglass for actions that take a lengthy amount of time.
  • When displaying pop-up menus on list boxes and list views, always select the item that is clicked before displaying the pop-up menu.
  • Use the proper type of message box for the situation.
    • To simply display non-critical information, use the information icon. (vbInformation)
    • To provide non-critical information that is still fairly important, use the exclamation icon. (vbExclamation)
    • To provide information that must absolutely be attended to, use the critical icon. (vbCritical)
    • To ask a user a question, use the question icon. (vbQuestion)
  • Avoid using technical jargon in a message box.




Much of this data was acquired from the following sources:

Microsoft's Practical Standards for Visual Basic    
By: James D. Foxall
ISBN: 0-7356-0733-8
Recommended Retail: $49.99

Microsoft MSDN Library

Personal experiences working with fellow developers.