Structured Coding Conventions
In addition to naming conventions, structured coding conventions,
such as code commenting and consistent indenting, can greatly improve
code readability.
Code Commenting Conventions
All procedures and functions should begin with a brief comment describing
the functional characteristics of the procedure (what it does). This
description should not describe the implementation details (how it
does it) because these often change over time, resulting in unnecessary
comment maintenance work, or worse yet, erroneous comments. The code
itself and any necessary inline comments will describe the implementation.
Remember the following points:
- Every important variable declaration should include an inline comment describing the use of the variable being declared.
- Variables, controls, and procedures should be named clearly enough that inline commenting is only needed for complex implementation details.
- At the start of the .bas module that contains the project's Visual
Basic generic constant declarations, you should include an overview
that describes the application, enumerating primary data objects,
procedures, algorithms, dialogs, databases, and system dependencies.
Sometimes a piece of pseudocode describing the algorithm can be
helpful.
Formatting Your Code
Because many programmers still use VGA displays, screen space should
be conserved as much as possible while still allowing code formatting
to reflect logic structure and nesting. Here are a few pointers:
- Standard, tab-based, nested blocks should be indented four spaces (the default).
- The functional overview comment of a procedure should be indented one space. The highest level statements that follow the overview comment should be indented one tab, with each nested block indented an additional tab.
Grouping Constants
Variables and defined constants should be grouped by function rather
than split into isolated areas or special files. Visual Basic generic
constants should be grouped in a single module to separate them from
application-specific declarations.
& and + Operators
Always use the & operator when linking strings and the + operator
when working with numerical values. Using the + operator to concatenate
may cause problems when operating on two variants.
vntVar1 = "10.01"
vntVar2 = 11
vntResult = vntVar1 + vntVar2 'vntResult = 21.01
vntResult = vntVar1 & vntVar2 'vntResult = 10.0111
Creating Strings for MsgBox, InputBox, and SQL Queries
When creating a long string, use the underscore line-continuation
character to create multiple lines of code so that you can read or
debug the string easily. This technique is particularly useful when
displaying a message box (MsgBox) or input box (InputBox) or when
creating an SQL string.
Program to find square root of a given number.
Private Sub Command1_Click ()
Me.Text2.Text = Sqr (CDbl (Me.Text1.Text))
End Sub