Hungarian Notation

[Previous] [Next]

Developers moved away from data type suffixes toward the use of single-character prefixes (for example, Dim lWidth As Long and Dim iHeight As Integer) . Prefixes make more sense because they are generally more intuitive than symbols and more of them are available. The single-digit prefix became popular but was doomed from the beginning. There are only 26 unique characters (a-z) available for single-character prefixes (still more than the number of available symbols), but there are many different types of variables and objects, and many of them share the same first letter.

A better naming convention eventually replaced the single-character prefix. This conventionusing a three-character prefix to denote data types and control typesis known as Hungarian notation, partly because its creator, Charles Simonyi, was originally from Hungary, and partly because these prefixes tend to make variable names look like a foreign language. Prefixes can grow in length as additional information is denoted, such as scope or the fact that a variable is an array. Although the standard prefixes are usually three characters, with the possible addition of modifiers, conventions using larger prefixes are also referred to as Hungarian notationHungarian notation is a concept, not a specific implementation.

In Hungarian notation, a unique three-character prefix is assigned to each data type and to each type of control. The three characters allow for plenty of versatility and for prefixes that are logical and intuitive. Look at the following Dim statements and you'll see how the prefixes align fairly intuitively with the variables' assigned data types:

  Dim  strName  As   String   Dim  intAge  As   Integer   Dim  lngMiles  As   Long   Dim  curSalary  As   Currency  

Now consider once again the code statement shown earlier:

 TotalDue = LineItemTotal _ Discount + TotalTax 

Each of the following statements is a possible equivalent of the previous statement. Three-character prefixes have been added. Also, for clarity, control references show their default properties.

 txtTotalDue.Text = curLineItemTotal _ txtDiscount.Text + curTotalTax curTotalDue = curLineItemTotal _ curDiscount + curTotalTax txtTotalDue.Text = txtLineItemTotal.Text _ txtDiscount.Text + _                    txtTotalTax.Text 

As you can see, prefixes make the statements much more understandable. Simply reading the statement tells you everything that is happening; you don't have to look at variable declarations to determine what's going on.

NOTE
There may well be no topic that causes more polarization among programmers than the use of Hungarian notation to denote type and scope. I firmly and unequivocally believe in the use of Hungarian notation and have personally enjoyed the benefits it provides.

Denoting a Variable's Data Type

The following table lists the prefixes you can use to denote a variable's data type.

Prefixes for Variable Data Types

Data Type Prefix Example
Boolean bln blnLoggedIn
Currency cur curSalary
Control ctl ctlLastControl
Double dbl dblMiles
ErrObject err errLastError
Single sng sngYears
Handle hwnd hwndPicture
Long lng lngOnHand
Object obj objUserTable
Integer int intAge
String str strName
User -defined type udt udtEmployee
Variant (including Dates) vnt vntDateHired
Array a astrEmployees

The obj prefix should be reserved for use when a specific prefix isn't suited. The most common use of this prefix is when referencing the Automation libraries of other applications. For instance, when automating Microsoft Word, you create an instance of Word's Application object. Since no prefix has been designated specifically for Word objects, obj works just fine, as shown in the following statement:

  Dim  objWord  As  Word.Application 

User-defined data types (UDTs) are custom data structures. Your ability to create objects has rendered UDTs unnecessary in many cases, but you'll probably still have occasion to use a UDT. User-defined data types are composed of multiple variables, often of different types. When defined, the UDT should be prefixed with type_ . However, each of the variables that make up the UDT should include the prefix of its typeor no prefix at all. Although it's generally a good idea to give the variables a prefix, some developers feel that doing so detracts from the object-oriented feel of using a UDT. If you use the Microsoft Windows API (application programming interface)and you really shouldyou'll note that the Windows API types don't use prefixes on the member variables. As with all aspects of applying standards, whichever method you choose, apply it consistently. The following code shows two possible ways to create a custom user-defined data type:

  Private   Type  type_Printer    DriverName  As String  DeviceName  As String  Port  As String  Copies  As Integer  Orientation  As Long End Type Private Type  type_Printer    strDriverName  As String  strDeviceName  As String  strPort  As String  intCopies  As Integer  lngOrientation  As Long End Type  

When creating a variable to hold a user-defined data type, use the udt prefix. Unfortunately, udt doesn't tell you anything about the specific UDT that it holds, but since the possibilities are endless and vary from program to program, it's impossible to assign them specific prefixes. The following statement is a sample declaration of the type created previously:

  Dim  udtPrinter  As  type_Printer 

Prefixing a variable as an array is different from prefixing other types of variables. You use a to denote that the variable is an array, but you then follow a with the prefix for the array's data typefor example:

  Dim  asngGrades(9)  As   Single  

Denoting a Variable's Scope

In addition to prefixing a variable to denote its data type, you can and should use a prefix to denote its scope. This scope designation character precedes the data type prefix and is separated from it by an underscore . For example, to denote a module-level string variable, you can use a statement such as:

  Dim  m_strName  As   String  

Prefixes for Variable Scope

Prefix Description Example
g Global g_strSavePath
m Local to module or form m_blnDataChanged
st Static st_blnInHere
(no prefix) Nonstatic, local to procedure intIndex

Other Prefixes

Prefixes aren't just for variables. All standard objects (including forms and controls) have a three-character prefix, as shown in the chapter's remaining tables. Learn and use these prefixes consistentlyif you're not already. Correctly applying the standard three-character prefixes to all of your variables and objects makes your code more self-documenting and easier to maintain.

Prefixes for Standard Controls

Control Prefix Example
Check chk chkPrint
Combo cbo cboTitle
Command cmd cmdCancel
Data dat datBiblio
Directory list box dir dirSource
Drive list box drv drvTarget
File list box fil filSource
Frame fra fraLanguage
Form frm frmMain
Group push button gpb gpbChannel
Horizontal scroll bar hsb hsbVolume
Image img imgIcon
Label lbl lblHelpMessage
Line lin linVertical
List box lst lstResultCodes
MDI child form mdi mdiContact
Menu mnu mnuFileOpen
OLE container ole olePhoto
Option button opt optSpanish
Panel pnl pnlSettings
Picture box pic picDiskSpace
Picture clip clp clpToolbar
Shape shp shpCircle
Text box txt txtAddress
Timer tmr tmrAlarm
Vertical scroll bar vsb vsbRate

Prefixes for ActiveX Controls

Control Prefix Example
Common dialog dlg dlgFileOpen
Communications com comFax
Data-bound combo box dbc dbcContacts
Grid grd grdInventory
Data-bound grid dbg dbgPrices
Data-bound list box dbl dblSalesCode
List view lvw lvwFiles
MAPI message mpm mpmSentMessage
MAPI session mps mpsSession
MCI mci mciVideo
Outline out outOrgChart
Report rpt rptQtr1Earnings
Spin spn spnPages
Tree view tre treFolders

Prefixes for Database Objects

Object Prefix Example
Database db dbCustomers
Field (object or collection) fld fldLastName
Index (object or collection) idx idxAge
QueryDef qry qrySalesByRegion
Recordset rst rstSalesByRegion
Report rpt rptAnnualSales
TableDef tbl tblCustomer


Practical Standards for Microsoft Visual Basic
Practical Standards for Microsoft Visual Basic .NET (Pro-Developer)
ISBN: 0735613567
EAN: 2147483647
Year: 2000
Pages: 57

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net