Descriptive Naming

Is the Basic programming language easy to read or hard to read? It depends on who you talk to, what your background is, and how clean your programming habits are. In the old days, line numbers and GOTO statements made it easy to create obscure spaghetti code. Fortunately, today's versions of Basic are much more structured and object oriented, although you can still mangle the readability of your code if you really want to!

A lot of suggestions for standard coding style have been floated over the past few years, some good and some not so useful. In my opinion, it's not worth getting uptight about. If you will get into the habit of using a few relatively simple and standard techniques, you can gain a reputation for creating easy-to-read code. If you're part of a team programming effort, which often seems to be the case for Visual Basic programmers today, efforts at making code easier to read can greatly enhance productivity.

Control Prefixes

One of the easiest techniques to master is naming each control with a standard prefix that identifies references to the control in the source code. This really does improve the readability of your code. Consider, for example, an event-driven procedure named Buffalo_Click. Does this refer to a command button? A picture? An option button? Until you figure out just what object on the form the name refers to, you are pretty well buffaloed. However, cmdBuffalo_Click is easily recognized as belonging to a command button, picBuffalo_Click belongs to a picture, and so on. A widely accepted list of standard prefixes has already been published in several places, and I'll repeat the list here with some additions to help propagate the standard.

Component-Naming Prefix Conventions for Visual Basic
Prefix Component
ado ADO Data
ani Animation
cal Calendar
cbo Combo box
ch Chart
ch3 3D check box
chk Check box
clp Picture clip
cm3 3D command button
cmd Command button
com Comm
con Container (DAO)
ctr Control (specific type unknown)
dat Data
db Database (DAO)
dbc DataCombo
dbd DataGrid
dbe Database engine (DAO)
dbgrd Data Bound Grid
dbl DataList
dir Directory list box
dlg Common dialog box
doc Document (DAO)
drv Drive list box
drp DataRepeater
dtp DTPicker
fil File list box
fld Field (DAO)
flex Hierarchical FlexGrid
fr3 3D frame
fra Frame
frm Form
fsb FlatScrollBar
gau Gauge
gpb Group push button
gra Graph
grd Grid
grp Group (DAO)
hdr Header
hsb HScrollBar
ils ImageList
img Image
imgcbo ImageCombo
ix Index (DAO)
key Key status
lbl Label
lin Line
lst List box
lsw ListView
lwchk Lightweight check box
lwcbo Lightweight combo box
lwcmd Lightweight command button
lwfra Lightweight frame
lwhsb Lightweight horizontal scrollbar
lwlst Lightweight list box
lwopt Lightweight option button
lwtxt Lightweight text box
lwvsb Lightweight vertical scrollbar
mci Multimedia MCI
med Masked Edit
mnu Menu
mpm MAPIMessages
mps MAPISession
mst Tabbed Dialog
mvw MonthView
ole OLE
op3 3D option button
opt Option button
out Outline
pic Picture box
pnl 3D panel
prg ProgressBar
prm Parameter (DAO)
qry QueryDef (DAO)
rd RemoteData
rec RecordSet (DAO)
rel Relation (DAO)
rtf RichTextBox
shp Shape
sld Slider
spn Spin button
sta StatusBar
ssys SysInfo
tbd TableDef (DAO)
tbs TabStrip
tlb Toolbar
tmr Timer
tre TreeView
txt Text box
usr User (DAO)
vsb VScrollBar
wsp Workspace (DAO)

Variable Names

Some people, particularly those coming from the world of C programming, suggest naming all variables using Hungarian Notation prefixes, which are similar to the control prefixes listed above. I have mixed feelings about this technique. On the one hand, it's nice to know what type of variable you're dealing with as you read it in the code, but on the other hand, this can sometimes make for cluttered, less readable syntax.

Since day one, Basic programmers have had the option of naming variables using a suffix to identify the data type. For example, X% is an integer, X! is a single-precision floating-point number, and X$ is a string. It's a matter of opinion whether these are better names than those using Hungarian Notation prefixes. I've even seen schemes for keeping track of the scope of variables using part of the prefix, which is an advantage of Hungarian Notation, but this much detail in the name of a variable might be overkill.

The following table lists the suffixes for various data types. It also lists the newer data types, which have no suffix, supporting my contention that Microsoft is heading away from the use of these suffixes.

Standard Suffixes for Data Types
Suffix Data Type
% 2-byte signed integer
& 4-byte signed integer
@ 8-byte currency
! 4-byte single-precision floating-point
# 8-byte double-precision floating-point
$ String
None Boolean
None Byte
None Collection
None Date
None Decimal (a 12-byte Variant)
None Object
None Variant

You might think that Hungarian Notation prefixes for all variable names are an absolute must, so I'll list the suggested prefixes here. Notice that some data types are indicated by more than one prefix—this lets you keep track of the intended use of the variable. For example, the standard 16-bit signed integer data type can be called Boolean, Handle, Index, Integer, or Word, depending on how you want to look at a given variable.

Hungarian Notation Prefixes for Data Types
Prefix Data Type
bln Boolean
byt Byte
cur Currency
dbl Double
dec Decimal
dtm Date (Time)
sng Float/Single
h Handle
i Index
lng Long
int Integer
obj Object (generic)
str String
u Unsigned quantity
ulng Unsigned Long
vnt Variant
wrd Word

The Object data type refers only to generic objects, not to specific objects that you know the name of—for example, a procedure might receive an object as a parameter but might not know what type of object it is. When you do know an object's type, use a prefix based on the object's class name. (See the section "Class Names" below for more information.)

Variable Declarations

As mentioned at the beginning of this chapter, one very important technique for keeping track of variable names is the use of the Option Explicit statement. You can choose to automatically add the Option Explicit statement whenever a new module is created, and I'd strongly recommend using this option. From the Tools menu, choose Options, select the Editor tab, and check the Require Variable Declaration check box.

The Option Explicit statement forces you to declare all variables before they are referenced. The Dim statement for each variable is an excellent place to explicitly declare the data type of the variable. This way, a variable name can be easy to read and easy to differentiate from the names of controls and other objects that do have prefixes, and its type can be easily determined by a quick glance at the block of Dim statements at the head of each module or procedure.

WARNING

A very common and dangerous mistake, especially for those familiar with the C programming language, is to incorrectly combine the declarations of several variables of one data type into one statement. This won't cut the mustard! You must explicitly define the data type for each variable in a Dim statement. Read on!

The following explicit variable declarations are all OK, and you'll get what you expect:

Dim intA As Integer, sngB As Single, dblC As Double
Dim D%, E!, F#

However, the following declaration will create two Variant variables (intI and intJ) and one Integer variable (intK) instead of the expected three Integer variables:

Dim intI, intJ, intK As Integer

Your program might or might not work as expected, and the reason for any unexpected behavior can be very hard to track down.

Menus

There are several schemes for naming menu items. I've chosen to name all menu items with the now-standard mnu prefix. You might want to add letters to identify which drop-down menu a given menu item is associated with. For example, a menu item named mnuHelpAbout refers to the About item selected from the Help menu. I've chosen to keep things slightly simpler—I usually shorten the name to something like mnuAbout. When you see mnu as a prefix in the source code in this book, you'll know immediately that it's a menu item. It's usually quite simple to figure out where in the menu structure the item is positioned, so I don't confuse the issue with extra designators.

Class Names

When creating new classes, forgo a prefix and name the class descriptively; when declaring object variables, use a prefix that designates its class. Typically, a unique three-character prefix is used for object variables, but if necessary, use a longer prefix to be more descriptive. In other words, create your own object-naming scheme. Microsoft suggests using whole words and standard capitalization when naming classes, as shown in the following table.

Examples of Class-Naming and Object Variable-Naming Conventions
Class Name Object Variable Name Prefix Sample Object Variable Name
Loan lon lonBoat
Planet plnt plntEarth
EmployeeRecord erc ercSales
DailySpecial dspec dspecTuesday