December 15, 2004
VB.Net/asp.net coding specification
It is very important to maintain a good coding specification in development. The new VB.Net/asp.net coding specification I have adopted is a certificate specification that proved to significantly improve code readability and help code management, classification. This coding specification is used to avoid the use of a long prefix from the Hungarian nomenclature to facilitate memory variables. The following introduction This coding specification is described.
First, named type of unit
1, class
□ The class declared by the class must be named, reflecting the role of nouns or noun phrases. Such as:
Class Indicator □ When the class is a characteristic (Attribute), at the end of Attribute, when the class is an exception, the EXCEPTION ends:
Class ColorseTexception
Class CauseexceptionAttribute □ When the class only needs an object instance (global object, such as Application et al, etc.) must end with Class, such as
Class ScreenClass
Class SystemClass □ When class is only used as a base class, according to the situation, the end is ended at the end of the BASE:
Mustinherit Class IndicatorBase □ If the defined class is a form, then the following must be added to the suffix form, if it is a web form, you must add a suffix Page:
Class Printform: Inherits Form '* Windows Form
Class StartPage: Inherits Page '* Web Form
2, enumeration and structure
Also must be named in noun or noun phrases. It is best to reflect the characteristics of enumeration or structure, such as:
Enum colorbuttons '' ends with complex, indicating this is an enumeration
Structure customer customerinforecord '' ends with RECORD indicating this is a structure
3, delegation type
□ The normal delegate type is named after the name of the action, to reflect the function of delegate type instance:
Delegate Sub Dataseeker (Byval Seekstring AS String) □ Used for the delegation type of event processing must end with EventHandler, such as:
Delegate Sub DatachangeDeventHandler (Byval E AS DatachangeDeventArgs)
4, interface
Unlike other types, the interface must be used as a prefix, and is named with adjective, how to highlight the class that implements the interface.
Interface isortable
5, module
The module is not type. His name must be named Module in addition to the name of the noun.
Module SharedFunctionsModule
The common feature of all of the above rules is that the words of each composition name must be the beginning of the uppercase, and the names of complete uppercase or lowercase are prohibited.
Second, method and attribute naming
1, method
Whether it is a function or a subroutine, the method must be named by verb or verb phrases. There is no need to distinguish functions and subroutines, and there is no need to indicate the return type.
Sub open (byval commandstring as string) Function setCopyNumber (Byval CopyNumber AS Integer)
The parameters need to indicate that byval is still byref, this is written to make the program edge long, but it is necessary. If there is no special situation, use ByVal. Named method of the parameter, refer to the "Name Method for Variable". The method that needs to be overloaded, generally does not write overloads, and write overloads as needed. 2, attribute
In principle, the field (field) cannot be disclosed, to access the value of the field, generally used attributes. The property is naming with a simple and clear noun:
Property Concentration AS SingleProperty Customer As Customertypes
3, event
The event is special attribute and can only be used in the event handling context. The principle of naming is generally the words of verbs or verbs, and through the time indicating the time of the incident:
Event Click AS ClickeventHandlerevent ColorChanged As ColorChangeDeventhangler
Third, variables and constants
The constant is named indicating the meaning of the meaning of the constant meaning, generally different types of constants:
Const defaultconcentration as sales = 0.01
In the strict requirements, the constant starts with C_, such as c_defaultconcentration, but it is best not to use it, it will bring difficulty.
Ordinary type variables, as long as nammetry with meaningful names, can not use the referreditter ornamental name, such as A, X1, etc., the following example is given below:
DIM INDEX AS INTEGERDIM NextMONTHEXPENDITURE As Decimal
DIM Customername As String
You can't get too long, you should try as simple as possible, as follows:
Dim variableusedtostoresysteminformation as string '' * error, too complicated
DIM systemInformation as string '' * is correct, simple and clear
DIM SYSINFO AS STRING '' * Error, too simple
Special circumstances can consider a letter of a variable:
DIM G AS Graphic
For controls, you should indicate the type of control, the method is to be classified directly behind the variable:
Friend WitHevents NextPageButton As Button '* Button Friend Withevents ColorchoicerPanel As Panel' '* Edition Friend Withevents CardFileOpendialog As FileOpendialog' '* File Open Dialog
Wait, there is no need to specify a prefix of a type of variable, just write the type it will be written later, try comparison the following code:
BTNCANCEL.TEXT = "& Cancel" cancelButton.text = "& ca Zancel"
Obviously the latter makes the reader understand the type of variables.
Fourth, prefix
1, object
1) Standard object
System.ArrayarrarrUsers user name prefix example shows whether the collection System.BooleanblnblnDoesUserExist user exists System.BytebytbytStreamContent byte stream content System.CharchrchrKeyPress button System.DateTimedtedteCreatedDateTime creation date System.DecimaldecdecYearlySaleQuota the total amount of annual sales System.DoubledbldblTotalPrice System.IntergerintintMessages number of messages System.ObjectobjobjExternalFunction external features System.SinglesngsngFinishRate completion rate System.StringstrstrLoginName login user name System.ExceptionexcexcRet error System.EnumenmenmUserStates state employees StructurestustuEmployees type System.Data.SqlClient.SqlConnectioncnncnnDatabase database connection System.Data.SqlClient.SqlCommandcmmcmmUserAddUpdate users to add updated System.Data.SqlClient.SqlDataAdaptersdasdaUsers User Data Adapter System.Data.SqlClient.SqlDataReadersdrSDRUSERDATA User Data Reader 2) Custom Object
We specify that the prefix of the object type should be determined according to the name of the custom object, as follows:
Object: sysset
Prefix: SS
Example: Sssafety
2. Depending on the variable and constant living cycle, we should define different living cycle prefixes to distinguish between this variable / constant.
a) class, module, component, control
We specify that the survival cycle prefix of the variable should be added "M _" (Module-Module) within the class, module, component, and control range. The example is as follows:
System.Arraym_arrm_arrUsers user name prefix example shows whether the collection System.Booleanm_blnm_blnDoesUserExist user exists System.Bytem_bytm_bytStreamContent byte stream content System.Charm_chrm_chrKeyPress button System.DateTimem_dtem_dteCreatedDateTime creation date System.Decimalm_decm_decYearlySaleQuota the total amount of annual sales System.Doublem_dblm_dblTotalPrice System.Intergerm_intm_intMessages number of messages System.Objectm_objm_objExternalFunction external features System.Singlem_sngm_sngFinishRate completion rate System.Stringm_strm_strLoginName login user name System.Exceptionm_excm_excRet error System.Enumm_enmm_enmUserStates state employees Structurem_stum_stuEmployees type System.Data.SqlClient.SqlConnectionm_cnnm_cnnDatabase database connection System.Data.SqlClient.SqlCommandm_cmmm_cmmUserAddUpdate users to add updated System.Data.SqlClient.SqlDataAdapterm_sdam_sdaUsers User Data Adapter System.Data.sqlclient.sqlDataReaderm_SDRM_SDRUSERDATA User Data Reader
b) Process, functions, attributes, events
We specify that in process, functions, attributes, event ranges, the variable's survival cycle prefix should add "O _". Examples are as follows: the user name prefix examples System.Arrayo_arro_arrUsers whether the collection System.Booleano_blno_blnDoesUserExist user exists System.Byteo_byto_bytStreamContent byte stream content System.Charo_chro_chrKeyPress button System.DateTimeo_dteo_dteCreatedDateTime creation date System.Decimalo_deco_decYearlySaleQuota annual sales System.Doubleo_dblo_dblTotalPrice System.Intergero_into_intMessages number of messages in the total amount System.Objecto_objo_objExternalFunction external function System.Singleo_sngo_sngFinishRate completion rate System.Stringo_stro_strLoginName login user name System.Exceptiono_exco_excRet error System.Enumo_enmo_enmUserStates state employees Structureo_stuo_stuEmployees type System.Data.SqlClient.SqlConnectiono_cnno_cnnDatabase database connection System.Data.SqlClient.SqlCommando_cmmo_cmmUserAddUpdate users to add updated System.Data. Sqlclient.sqldataadaptero_sdao_sdausers User Data Adapter System.Data.sqlclient.sqlDataReadero_SDRO_SDRUSERDATA User Data Reader
Five, label
The label is the code identifier used for GOTO jumps, because GOT is not recommended, the label is used is more demanding. The label must be on top of the upper capital, the middle space is used underline _ instead, and should be _ beginning, such as:
_A_label_example:
This definition tag is to distinguish from other code elements.
Six, name space
Typically, a project uses a name space, usually does not need to use the Namespace statement, but specified in the "root namespace" of the project option, using the root namespace can make the code more neat, easy to modify, this is the advantage of VB full. The syntax of the namespace is:
Company name. Product name [. Component name]
Such as:
Namespace com.neetnamespace com.file.io.files
Just starting a name space, the name is definitely not a good idea, be sure to comply with the above provisions.
Seven, formatted
Good formatting code has considerable benefits to our browsing and maintenance.
1, block
.NET provides #REGION ... # End Region block control. We should classify and organize it according to the functionality implemented by the code.
2, indent
Each level should directly indent in Tab instead of the SPACE.
3, stream
Each method, function, attribute, event should have only one entry and an exit. If you need a multi-layer nested and need to be jumped out, use a local Boolean or an Integer variable to indicate that multi-layer jump out.
for example:
Private function testforreturn () as boolean
DIM O_BLNRET As Boolean = FALSE
DIM I AS INTEGER, L AS INTEGER
FOR i = 1 to 100
For l = 1 to 10
IF (x) THEN
o_blnret = true
EXIT for
Else
END IF
Nextif o_blnret kil
EXIT for
Else
END IF
NEXT
Return o_blnret '' here is the only exit
END FUNCTION
Eight, note
1, guidelines
There are many rules of the annotation. Basic: normal comments start with '' *, alone 'only uses code for temporary unused code
'' * This is a normal annotation '' * This code is added after debugging correct (i) = true kil ....
This makes it easy to use the code annotation tool to control the use of code.
2, class (including WebForm, WinForm, etc.), modules, components, controls
Each class, module, component, and controls must enter the information of the object, the sample content and format are as follows:
'' ********************************************************* ******************
'' *
'' * Object Name: OnlineUpdateService
'' * Name Space: http://www.domain.cn/onlineUpdate/onlineUpdateService.asmx
'' * Author: CHS (Wilson Chan)
'' * Function Description: Online Update Web Services
'' * Create Date:
20
03/07/27
'' * Modification Date: 2003/09/5 16:59
'' * Modified record:
'' * □
20
03/07/31
'' * 1.addupdateUsercategory / deleteusercategory
'' * 2.addupdateUserstate / deleteuseuserstate
'' * 3.addupdateServerUpdate / deleteServerUpdate
'' * 4.addupdateclientUpdate / deleteclientupdate
'' * 5.addupdateclientUpdatelog / deleteclientUpdatelog
'' * 6.GetServerUpdates / getClientUpdates / getClientUpdatelogs
'' *
'' ********************************************************* ******************
In general, we ask for content: object name, namespace, authors, function description, creation date, modification date, modification record, especially, we require modification records to detail the recent revision.
3, methods, functions, events and properties
Each method, function, event, and attribute, the first place, must enter the information of the object, the sample content and format are as follows:
'' * Name: OnlineUpdateFileaddupdate
'' * Function: Add Change Update Information
'' * Author: chs
''*create:
20
03/7/31
''*modify:
20
03/7/31
'' * Parameters: intid: Unique indicator '* startle: title
'' * StrVersion: version
'' * StrVerifier: Name
'' * StrDescription: Description
'' * StrrelatedFile: related files
'' * StrupdatePackage: Download Pack
'' * IntState: Status
'' * DtecreatedDateTime: Create Date
'' * Back: Success, True, Instead, False
'' * Description:
Generally, we require: name, function, author, description, creation, modification, parameter and return.
Eight, integrity
1, IF ... Else ... End IF
2, SELECT CASE ... CASE ELSE ... END SELECT
Nine, safety
1, Try ... catch ... finally ... End Try
Ten, optimization
1, with
2, for ... next
3, Do Until ...
Loop
4, code reconstruction
Eleven, other
1, shortcut
2,