[Repost] Seven good habits of VB programming

xiaoxiao2021-03-06  63

1, "&" Replace " " 2, variable name sensation, statement is wrong, source code maintenance, please develop the following "Object Naming Convention" Good habits 4, in simple selection conditions, use IIF () function 5, try to use debug.print for debugging 6, try to use the message icon as possible when repeating the properties of an object, try to use the message icon as much as possible as possible, this program is more specified 8 Using Enumeration 1, "&" replace " " in many people's programming languages, using " " to connect to the string, which is prone to ambiguity.

Good habits are "&" to connect to the string. Not correct: DIM SMESSAGE AS STRINGSMESSAGE = "1" "2" correct: Dim SMESSAGE AS STRINGSMESSAGE = "1" & "2" Note: "&" Space 2, variable name case, statement is wrong, source code maintenance, the following two codes: Read the difficulty code: DIM sname as stringdim nturn as integerif NTURN = 0 Thenif Sname = "vbeden "ThenDo While nTURN <4NTURN = nTURN 1LoopEnd IfEnd If the code is easily understood: Dim sName As StringDim nTurn As IntegerIf nTurn = 0 Then If sName =" vbeden "Then Do While nTurn <4 nTurn = nTurn 1 Loop End IfEnd If [Return to index] 3, please develop the following "Object Naming Convention" Good habits Recommended Control Prefix Control Type Prefix Example 3D Panel PNL PNLGroup Ado Data Ado Adobiblio Animated Button Animailbox Check Box ChkReadonly Combo Box, Drop-Down List Box CBO CBOENGLISH Command Button CMD CMDEXIT Common Dialog DLG DLGFILEOPEN Communications COMFAX Control (used in the process) when a specific type is unknown

ctr ctrCurrent Data dat datBiblio Data-bound combo box dbcbo dbcboLanguage Data-bound grid dbgrd dbgrdQueryResult Data-bound list box dblst dblstJobType Data combo dbc dbcAuthor Data grid dgd dgdTitles Data list dbl dblPublisher Data repeater drp drpLocation Date picker dtp dtpPublished Directory list box dir dirSource Drive list box drv drvTarget File list box fil filSource Flat scroll bar fsb fsbMove Form frm frmEntry Frame fra fraLanguage Gauge gau gauStatus Graph gra graRevenue Grid grd grdPrices Hierarchical flexgrid flex flexOrders Horizontal scroll bar hsb hsbVolume Image img imgIcon Image combo imgcbo imgcboProduct ImageList ils ilsAllIcons Label lbl lblHelpMessage Lightweight check box lwchk lwchkArchive Lightweight combo box lwcbo lwcboGerman Lightweight command button lwcmd lwcmdRemove Lightweight frame lwfra lwfraSaveOptions Lightweight horizontal scroll bar lwhsb lwhsbVolume Lightweight list box lwlst lwlstCostCenters Lightweight option button lwopt lwoptIncomeLevel Lightw eight text box lwtxt lwoptStreet Lightweight vertical scroll bar lwvsb lwvsbYear Line lin linVertical List box lst lstPolicyCodes ListView lvw lvwHeadings MAPI message mpm mpmSentMessage MAPI session mps mpsSession MCI mci mciVideo Menu mnu mnuFileOpen Month view mvw mvwPeriod MS Chart ch chSalesbyRegion MS Flex grid msg msgClients MS Tab mst mstFirst OLE container ole oleWorksheet Option button opt optGender Picture box pic picVGA Picture clip clp clpToolbar ProgressBar prg prgLoadFile Remote Data rd rdTitles RichTextBox rtf rtfReport Shape shp shpCircle Slider sld sldScale Spin spn spnPages StatusBar sta staDateTime SysInfo sys sysMonitor TabStrip tab tabOptions Text box txt txtLastName Timer TMRTMRALM TOOLBAR TLB TLBACTION TREEVIEW

Tre Treorganization Updown Upd Upddirection Vertical Scroll Bar vsb vsbrate ---------------------------------------- -------------------------------------- Recommended Data Access Objects (DAO) prefix with the following prefix indicating data access object database object prefix example Container con conReports database db dbAccounts DBEngine dbe dbeJet Document doc docSalesReport Field fld fldAddress Group grp grpFinance Index ix idxAge Parameter prm prmJobCode QueryDef qry qrySalesByRegion Recordset rec recForecast Relation rel relEmployeeDept TableDef tbd tbdCustomers User USR USRNEW Workspace WSP Wspmine ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------- Application frequently uses many menu controls, with a set of unique sets for these controls Naming conventions are very practical. In addition to the top "MNU" tag, the prefix of the menu control should be extended: add an additional prefix for each stage, put the header of the final menu in the last menu. The following table lists some examples. When the recommended prefix menu menu menu title sequence processor name File Open mnuFileOpen File Send Email mnuFileSendEmail File Send Fax mnuFileSendFax Format Character mnuFormatCharacter Help Contents mnuHelpContents when this convention, all members of a particular menu group one by one column In the "Properties" window of Visual Basic. Moreover, the name of the menu control clearly shows the menu items they belong. Selecting a prefix for other controls For controls listed above, the unique prefix consisting of two or three characters should be standardized to maintain consistency. More than three characters are used only when it is necessary to clarify. Constants and variable naming conventions In addition to objects, constants and variables also require a good format naming convention. This section lists the recommendations of constants and variables supported by Visual Basic. And discuss issues that identify data types and ranges. Variables should always be defined within a small range as possible. The global (public) variable can lead to extremely complex state agencies, and make the logic of an application very difficult to understand. Global variables also make the reuse and maintenance of the code more difficult. Visual Basic's variables can have the following range declaration position visible location process grade, 'private' during the process of declaration, in the declaration of modular-level forms or code modules (.frm, .bas) In the 'private' form or code module, each process of the global code module (.bas) declaration part of the 'Public' application in Visual Basic's application, only if there is no other The convenient way to use global variables when sharing data between the form. When you have to use global variables, they declare them in a single module and packet according to the function. Take a meaningful name to this module to indicate its role, such as public.bas. Good coding habits are to write modular code as much as possible. For example, if the application displays a dialog, all controls and code you want to complete this dialog task are placed in a single form.

This helps to use the application's code organization in useful components and reduce the overhead of its runtime. In addition to global variables (should be not delivered), processes and functions should only be operated only for objects passed to them. The global variable used in the process should be identified in the declaration section of the process start. In addition, you should deliver parameters to the SUB process and the Function process, unless it is clear that the passed parameter value is changed. With the growth of project size, the work of dividing variable ranges is also increased. The single-alphabet prefix is ​​launched in front of the type prefix indicates this growth, but the length of the variable name does not increase. Variable range prefix range prefix example global G GStrUsername Module M MBLNCalCinProgress Local to Process No DBLVELOCITY If a variable is declared in a standard module or form of public, then the variable has a global range. If a variable is declared as private in a standard module or form module, then the variable has a modular level. Note: Consistency is a key to use this technology. The syntax inspector in Visual Basic does not capture module-level variables starting with "p.". The main body of constant places is mixed, and the first letter of each word is capitalized. Although standard Visual Basic constants do not contain data types and range information, prefixes such as I, S, G, and M are still very useful for understanding the value and range of a constant. For constant names, the same rules as variables should be followed. For example: MintUserListMax 'for the maximum limit of the user list' (integer value, local to module) GSTRNEWLINE 'new row character' (string, application global use) variable declares that all variables will save programming time, because the type of operation is caused The error is reduced (for example, is AUSERNAMETMP or SUSERNAMETMP, or SUSERNAMETEMP). In the Editor tab of the Options dialog, check the "Requirements Variable Declaration" option. Option EXPLICIT statement requires that all variables are declared in the Visual Basic program. It should be given to the variable to indicate their data type. Moreover, the prefix can be expanded to indicate the range of variables, especially for large programs. Use the following prefix to indicate the data type of a variable. Variable Data Type Data Type Prefix Example String (String Type) STRFNAME INTEGER (Short Negative Type) Int IntQuantity Long (Long Integer Type) LNG LNGDISTANCE SINGLE (Single Quick Floating Point Type) SNG SNGAVERAGE DOUBLE (Double Accuracy Floating Point Type) DBL dblTolerance Boolean (Boolean) bln blnFound byte (byte type) byt bytRasterData date (date type) dte dteNow Currency (currency type and fixed-point calculations) cur curRevenue Object (object type) obj objCurrent variant (variant type) vnt vntCheckSum description The subjects of variables and process names or process names should be used in cases in size and should be long enough to describe its role. Moreover, the function name should be in one verb, such as initNameArray or Closedialog. For frequently used or long items, recommended

Use standard abbreviation to reason systemize the length of the name. In general, the variable name of more than 32 characters is difficult to read on the VGA display. When using a thumbnail, make sure they are consistency throughout the application. In one project, if you use CNT for a while, you will use count, which will result in unnecessary confusion. User-defined types in a big project with many user-defined types, often necessary to give each type of one of its own three characters prefixed. If these prefix starts with "U", quickly identify these types when using a user-defined type. For example, UCLI can be used as a prefix for a user-defined customer type variable. [Return index] 4. Under simple selection conditions, use the IIF () function Rosoto code: if nnum = 0 Then Sname = "SANcy" else sname = "xu" end if simple code: SNAME = IIF Nnum = 0, "Sancy", "XU") 5, try to use Debug.print to debug in many beginners debugging, use msgbox to track the variable value. In fact, Debug.print can not only achieve the same effect, but also During the final compilation process, MsGbox must be manually annotated or deleted. Usually: msgbox nName should: debug.print nName6, try to use with .... end with it when repeating the properties of an object Usually: form1.height = 5000form1.width = 6000form1.caption = "this is mylabel" should: with form1.Height = 5000 .width = 6000 .caption = "this is mylabel" End with this structural program is more efficient, Specially in the cycle statement. 7. Try to use the message icon as much as possible so that the program is specified in general. Vbinformation is used to prompt or successful messages vbexclamation. Return index] 8, the format of the enumeration enumeration in may be used in the case of [public | private] enum namemembername [= constantExpression] membername [= constantExpression] ... End Enumenum statement contains the following sections: Part Description PUBLIC options of. Indicates that the Enum type is visible throughout the project. The default situation of the Enum type is public. Private is optional. Indicates that the Enum type is only visible only in the declared module. Name must be. The name of the enum type. Name must be a legitimate Visual Basic identifier that specifies the type with this name when defining a variable or parameter of the enum type. MEMBERNAME is required. A legitimate Visual Basic identifier for specifying the constituent element name of the enum type. Constantexpression is optional. The value of the element (for long type). Can be an other ENUM type. If there is no ConstantExpression, the value is given or 0 (if the element is the first memory), or the value is larger than its direct forward. Note The so-called enumeration variable refers to a variable defined with an enum type. Variables and parameters can be defined as an ENUM type. Elements in the enum type are initialized to enum

转载请注明原文地址:https://www.9cbs.com/read-111383.html

New Post(0)