VB編程規範

 

 

 

VISUAL BASIC Standards




1.0        Introduction

1.1         Purpose

This document is a compendium of good programming practices that can be gainfully used while developing applications in Visual Basic (VB). They have been documented in order to ensure that experience gained in the usage of VB is available to other application developers. It is expected that over a period of time these practices will mature into conventions and programming guidelines.

It may be worthwhile to be read the following companion documents -- Guidelines for Good programming practices and Guidelines for developing Windows based user interfaces.

1.2         Scope of the Guideline

By default, guidelines prevalent in the customer organization are to be used while developing applications, unless there are compelling reasons for not doing so and the customer’s consent has been obtained.

This document is to be used for areas not covered by the customer guideline or in the absence of a customer guideline.

A project may adopt its own guidelines and conventions. These should be clearly documented and made available to all team members as well as quality personnel. Some of the items that may require project-specific conventions are -- naming conventions, standard screen structure (headers, footers, border etc.), report formats, date formats (DD/MM/YY, MM/DD/YY etc.), other user interface guidelines (for e.g., conventions for functions keys, standard exit and entry screens etc.), attributes of display items (position on screen, font, size, attributes, screen size, colors used, etc.).

1.3         Organization of the Document

The operative part of the document is spread over four sections -- Naming conventions, code organization, User interface and general programming rules. Each section is further sub-divided to facilitate easy reading.

1.4         Naming Conventions

The guideline outlines naming conventions for four types of entities -- procedures, VB Controls, DOS physical files, Variables and data types. These are listed in the following sub-sections.

1.4.1         Naming Procedures

Procedures in VB are of two types -- Form level procedures and General procedures.

Form level procedures can be further classified into Event procedures and Module procedures. Event procedures are automatically named by VB. Module level procedures should be named as follows: 

 <Action>_<Object>

For example, Insert_Student, Get Customer

All general procedures in Global file should have GLB as the prefix. The rest of the name should be indicative of the function of the procedure (verb) and the object on which it works.

For example, a general procedure for validating that all characters entered are numeric will have the name -- GlbCharValNum ()

All general procedures in other files should have a 2-character prefix for the menu title to which it pertains. The rest of the name should be indicative of the function of the procedure (verb) and the object on which it works.

Example:

A general procedure for disabling the command buttons individually in form1 of Files menu title will have the following name:

FlForm1DisBtn ()

1.4.2         Naming Control Items     

Object

Prefix

Example

Form

frm

frmBegin

Combo

cbo

cboShopCodes

CheckBox

chk

chkltalic

Command Button

cmd

cmdCancel

Data Control

dat

datShopDetailHeader

Drive List Box

drv

drvForm200s

File List Box

fil

filForm20Is

Frame

fra

fraGroupOptions

Grid

grd

grdCollectedData

Horizontal Scroll Bar

hsb

hsbBlue

Vertical Scroll Bar

vsb

vsbRed

Image

img

imgButterFly

Label

lbl

lblShopCode

Line

lin

linVertical

Listbox

lst

lstShopCodes

Menu

mnu

mnuAdd

Ole

ole

oleSource

Option Button

opt

optYes

Picture Box

pic

picLogo

Shape

shp

shpCircle

Text Box

txt

txtName

Timer

tmr

tmrTick

Panel

pnl

pnlFloodFill

Gauge

gge

ggeHourGlass

Database

db

dbShopOrder

Dynaset

ds

dsSelectedSet

Table

tb

tbParentChild

Bookmark

bm

bmFirstRecord

 

1.4.3         Naming DOS Physical Files

§         Global file should be named GLBxxxxx.bas where xxxxx is the name of the application

§         Code modules for each menu title should be named xxxxxxnn.bas where xxxxxx is the name of the menu title and nn are numbers to be used if the code is to be spread over different files later

§         Form modules should be named AABBBCCC.frm where AA is the abbreviation for menu title, BBB and CCC are abbreviations for the object and function of the form

1.4.4         Naming Variables

The convention for naming variables is outlined below:

Variable Type

Prefix

Local to procedure

l_

Form module level

f_

Code module level

m_

Static variable

s_

global variable

g_

generic object variable

og_

specific object variable

os_

1.5         Code Organization

Code should be organized as follows:

·         There should be ONE Global file which contains the following:

·         Project and Environment level statements (Example: Option explicit)

·         All Global variable declarations

·         All Global constant declarations

·         Common validation procedures for the entire application

·         General procedures

·         Common error handling procedures for the entire application

·         General procedures

·         There should be one Code module for each of the main menu titles of the application

·         This should contain general procedures for all common functions which are needed by each form in the application. However, these procedures should be ‘worker’ type procedures which perform a specific function. Selection of the procedure to be called should be done at the form level itself.

·         Each form should have code for all events on the form. Groups of Option buttons, Checkboxes, Command buttons, Menu items should be placed in a control array so that one procedure can be written for the entire control array

·         There are several include files provided with Visual Basic and MS SQL server which can be included as they are. For example, CONSTANT.TXT etc.

1.6         User Interface

The guiding principles for the user interface should be:

·         Simplicity

·         Consistency

·         Predictability.

Usage of too many colors should be avoided since its makes the interface look cluttered and also distracts the user. A consistent color scheme should be used throughout the application.

1.7         Menus

If menus are needed, a separator bar should be used to separate logical groups of functions.

1.8         Forms

The following guidelines are to be used:

·         Forms should be compact

·         An attractive and consistent color scheme should be used throughout the application

·         The size of the form should be so chosen that it does not hide display of minimized icons

·         If multiple forms are to be displayed, the cascading style of presentation should be used

·         The form should not be cluttered with too many fields. If necessary a separate form should be used

·         Forms for data entry / update should have a clear or drop function which clears the data entered / changes made and presents the same form again.

1.9         Dialog Boxes

·         Dialog boxes should be used where minimal user input is required

·         Dialog boxes should be movable but should not be capable of resizing, minimizing, maximizing

·         Dialog boxes should have a fixed border style throughout and should always appear in a fixed place

1.10   Controls - General

·         While referring to controls on another form, ! should be used

·         The property of a control should always be specified explicitly.

1.11   Command Buttons

·         As far as possible, command buttons should be placed horizontally, instead of vertically. This is because the natural movement of the eye is from left to right

·         The most likely command button should always be specified as the default command button.

1.12   Option Buttons

Option buttons should always be placed in a frame since it makes it easier to add another set of option buttons at a later date, if required.

1.13   Labels

Where some data is meant for display only, it is preferable to use labels.

1.14   Combo Boxes

Style 2, which is compact, should be generally used. If data has to be entered, other styles, preferably style 0, may be used.

1.15   Grids

The Column width of the columns should be specified in terms of the column width of the grid. This will ensure that device specific sizes are not used.

1.16   Help

Help should be provided at three levels - global level, form level, control level. The rules governing each level are outlined in the following paragraphs.

Level

Characteristics of Help Provided

Global

Should be as per the windows norm, with Help instructions, index of topics etc.

Form

Should display information about the functions of the form and the function of each command button

Control

All controls need not have help. Only controls where the user is expected to enter data or make a selection should have help

1.17   Status Bars

Status bars should be used to display messages to the user, where appropriate.

1.18   Visual Cues

The following visual cues MUST be provided to the user:

·         When a function is disabled the appearance of the control should change

·         When a dialog box is shown when a control is clicked, an appropriate visual cue should be shown on the control.

·         Any action by the user should have an immediate feedback to the user by displaying a message in the status / message bar. For example: Customer details added

2.0        General Programming Rules

2.1         Handling Variables

·         It is preferable to declare object variables as being of a specific type (instead of generic type). This is because generic type variables are resolved by VB at run time, resulting in slower and error prone operations

·         Naming variables with the same name as Form properties or controls should be avoided

·         All variables should be explicitly declared. This can be ensured by setting an option in the environment

·         Only one variable should be declared per line. Declaring multiple variables in a line should be avoided

·         Local variables have a life only within the procedure. If necessary, this life can be extended by declaring them as Static

·         To the extent possible, usage of global variables should be avoided. If it is not possible, then all Global variables should be declared in one place. This makes the code easier to maintain.

·         VB provides a Variant data type which can store different types of values at different times and VB provides automatic conversion. Though this appears to be quite flexible, it has the following problems:

·         Variant variables take up more space than required

·         Code execution is slower because of conversions done by VB

·         Operations lead to unexpected results because of the automatic         conversion done by VB.

·         Therefore, as far as possible, specific data types should be used. If the use of Variant cannot be avoided, then VarType function should be used to determine the internal representation. This returns values up to eight. It should be ensured that values greater than eight are handled gracefully as future versions may have them.

·         The + operator can be used for arithmetic operations as well as string concatenations. Since this make the code difficult to read, & operator should be used for String concatenations and + for arithmetic operations

·         To the extent possible, hard coding of values should be avoided by using Symbolic Constants. Symbolic constants should be in upper case and should            be declared at one place only

·         For example: MAX_NO_OF_ROWS           

·         Care should be taken to ensure that a circular reference is not set up between two or more symbolic constants.

·         While performing operations, if one is not sure about the data types (especially for variants) the data should be first converted to the desired type and then used in the operations.

·         Two different conventions are followed in specifying dates (MM/DD/YY and DD/MM/YY). To avoid confusion, numbers should not be used while comparing dates/times. It is preferable to indicate the month using literals (for example, JAN, FEB etc.).

2.2         Functions and Procedures

·         The arguments of a function should be declared with ByVal. This ensures that arguments are passed by Value rather than by reference, thus preventing modification of arguments within a function. Arguments should be passed by reference only when required

·         Alternatively, one can use CALL and enclose the arguments within parenthesis (This ensures that arguments are always passed by value)

·         Argument types in functions should be explicitly declared. If not declared, they are treated as Variant type

·         The data type of the value returned by the function also should be explicitly declared as far as possible. Otherwise, it is treated as a variant type

·         When making a function call, the values returned by the function should be checked before proceeding further.  This should cover cases of errors

·         Within a function, if an error occurs, the return value should be set to NULL. This ensures that wherever the return value is used will also evaluate to NULL. This makes error handling easier

·         Static variables should be used to pass flags etc. from one procedure to another

·         Declaring a procedure as static automatically makes all variables within the procedure as static. This should be avoided. Variables should be declared as static only when required

·         Local variables are stored in a stack, which has limited space. To avoid running out of stack space, local variables should be used judiciously

·         Local arrays should always be declared with Static not with Dim.

2.3         IF and CASE Statements

Two formats are supported while using IF statements. These are:

            IF (Condition) THEN

                        (Statements)

            ENDIF

            IF (Condition) THEN (Statements)

It is evident that the second format done not have an ENDIF and is less readable. Hence, only the first format should be used.

·         Care should be taken to ensure than an ELSE statement covers cases where none of the conditions are true. Certain fatal errors may be missed by not           having a ELSE statement

·         ELSEIF should be used with care. If it is being used to select one out of           several conditions then it may be advisable to use SELECT CASE instead

·         When using SELECT CASE, care should be taken to include CASE ELSE to cover cases not explicitly handled

·         To make case insensitive String comparisons, the Option COMPARE TEXT should be used in the modules

·         When the name of a control is changed it should be ensured that the corresponding event procedures written for the event are also changed (Name change). Otherwise they will be treated as General procedures and are likely to become ‘Dead’ code.

2.4         Inter Module Communication

When data has to be passed from one form module to another, the tag property can be used to pass data. A protocol has to be established whereby; each of the forms follows the protocol to pass data. Care should be taken to set the tag to an empty string after checking.

The only other alternative is through global variables.

2.5         Validations

Some databases provide for rules at database level that can be used for validation, but they are not so useful since they are invoked only when the entire data is sent for validation. In most applications it is desirable to validate as soon as the user starts entering data into a text box or as soon as the data entry is over. Also, in some cases, ‘prefield’ checks may have to be done. In such cases the GotFocus, TextChange, LostFocus events in VB should be used to perform validations. To ensure that code is not repeated, such validation procedures should be made Global to the extent possible. It should be ensured that field level validations do not impair the user’s facility to enter data in any order.

Wherever possible, functions provided by the language should be used to make basic validations on data entered in text boxes. For example: All characters only, all numeric only, all characters in upper case only etc. (KeyPress function). In some cases functions may have to be written.

2.6         Comments

Comments should be used liberally in the code. In particular comments MUST be used in the following:

Functions:

Functions should have the following included in the comments:

·         The purpose of the function

·         The description of each of the parameters

·         The description of each of the return values

·         SUCCEED and FAIL should be described as Global constants.

Subroutines:

Subroutines should have the following included in the comments:

·         The purpose of the subroutine

·         The description of each of the parameters.

Blocks of code:

All blocks of code should be commented.

Variables:

All variables other than simple variables like counters should be described in comments.

Exits:

All exits out of a subroutine or function should be clearly commented

Loops:

Where loops are nested, it is necessary to comment clearly the logic and conditions when the loop is exited.

2.7         Examples of Global Procedures

Disabling / Enabling / Hiding / Making visible a single control of a particular type on a form. There could be one procedure for each of the above functions and for each type of control. Argument is a single control name.

Example:         Disable <Command_button> procedure

                        Enable Text Box procedure

Disabling / Enabling / Hiding / Making visible all controls of a particular type on a form. There could be one procedure for each of the above functions and for each type of control. Argument is a single form name.

Example:         Disable all text boxes

                        Hide all Command buttons

2.8         Display of Original Selection 

When an update, details or delete form containing list boxes and / or combo boxes is shown, the original selection(s) chosen by the user should be highlighted.

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章