Turn: Delphi code standard document (mountain pig)

xiaoxiao2021-03-06  28

This document describes the general Delphi coding standard. In general, this document is primarily to provide a method for the development group, so that there is a consistent format in programming, so that the code written by each programmer in the development group can be understood by others. This requires everyone to use the consistent code style. This document does not have to include each detail of the code standard. But enough to get you can start working. You can freely use and modify these standards to meet different needs. However, we don't recommend that you spend too much on these standards. We introduce these standards because they may be familiar with Borland when new developers join the development group. Like most code standard documents, you can find the latest version of the help: http://www.xapware.com/ddg This document does not include the user interface standard. The user interface standard is independent of other standards and is equally important. A large number of books and Microsoft attractions contain instructions on this standard, so let's take a few more details. It is recommended that you go to Microsoft Developers Network and other possible land to see this information. 1. General source code format rules 1.1. Indentation indentation is two spaces in each stage. Do not save tabs in the source. This is because the width of the tab is different with different user settings and code management utilities (printing, documentation and version control, etc.). By using the Tools | Editor Options menu, on the General page, do not select the Use Tab Character and Optimal Fillk box, which is not saved; Block Ident and Tab STOPS are preferably set to 2.1.2. The distance is set to 8O characters. Sourcecodes generally do not exceed margins by writing a word, but this rule is more flexible. As long as it is possible, the statement that exceeds a row should be wrapped in a comma or operator. After the wrap, the two characters should be indensed. 1.3. Begin ... Endbegin statement must be occupied separately. For example, the first line below is wrong, and the second line is correct: for i: = 0 to 10 do begin // fault, Begin and for i: = 0 to 10 do // pair, Bogin is in addition A special situation in the REP This rule is that when Begin is part of the ELSE statement, for example, if someconditionStatement the beginning, END ELSE BEGIN SOMETHERSTATEMENT; END; END statement is always a line. When BeGin is not part of the ELSE statement, the corresponding End statement is the same as the reachable amount of the Begin statement. 2. Object pascal2.1. There is no space between the parentheses and the next character. Similarly, there is no space between the right brackets and the previous character. The following example demonstrates correct and incorrect spaces. CallProc (APARAMETER); // Flag CallProc (APARAMETER); // Do not include excess parentheses in the statement. In the source code, parentheses only use when needed. IF (i = 42) THEN / / wrong, brackets are redundant IF (i = 42) or (i = 42) THEN / / correct, must be used in parentheses 2.2. Reserved words and keywords Object Pascal language reserved words and key The word is always lowercase. 2.3. Process and Function (routine) 2.3.1. Named and format routines should start with uppercase letters and intergenever to increase readability.

Here is an incorrect: procedure thisisapoorlyformattedRoutinename; change to this is right: Pocedure thisismuchmorereadableRoutinename; routine name should be meaningful. The routine that performs actions is best coupled to the verb represents the verb represents the action of the action as a prefix: Procedure Formatharddrive; setting the input parameter value of the input parameter value should be prefixed as a set, for example: procedure setUsername; get the number of routines With GET, for example: function getUsername: string; 2.3.2. Conversion 2.3.2.1. Format As long as possible, the same type of shape should be collected together: Procedure Foo (Paraml, Param2, Param3: Integer; param4: String); 2.3.2.2. Name Names of Names should express its use. If appropriate, the name of the group is preferably prefixed in letter A, for example: procedure: string; meanserage: integer; prefix A is necessary when the parameter name is in the same name as the class, the prefix is ​​necessary. 2.3.2.3. Sequence sequential parameter parameter mainly consider register call rules. The most common parameters should be used as the first parameter, follow the left to right rows according to the frequency of use. The input parameter is before the output parameter. The large parameters should be placed before the range of small parameters. For example: SomeProc (Aplanet, Acontlnent, Acountry, ASTATE, ACITY); some exceptions. For example, in an event handle handle, the Snder parameter of the TOBJECT type is often the first parameter to be passed. 2.3.2.4. Convequential parameters To make records, arrays, short strings, or interface types of parameters cannot be modified by routines, the shape should be used in const. In this way, the compiler will generate a code in the most effective way to ensure that the passing parameters are not variable. If other types of parameters are desirable to be modified by routines, I can also marke with const. Although this has no effect on efficiency, this is more information to the caller's caller. 2.3.2.5. Name conflict When the two units contain the same name, if the routine is called, the routine that is actually called is the last unit in the Uses clause. To avoid this, you can add the desired cell name before the method, for example: sysutils.findclose (SR); or Windows.FindClose (Handle); 2.4. Variable 2.4.1. Variable Name and format variable name should be It can express its use. The cyclic control variable is often a single letter, such as I, J, or K. It is also possible to use more meaningful names, such as UserIndex. The Boolean variable name must be clearly indicating the meaning of true and false values. 2.4.2. Partial variable local variables are used in the routine and follow the naming rules of other variables. If needed, the variable should be initialized immediately at the entrance of the routine. The variable of the local Ansistring type will be initialized to an empty string, a variable of the local interface and scheduling interface type, automatically initialized to NIL, the local Variant and Olevariant type variables are automatically listed to Unassigned. 2.4.3. Global variables generally do not encourage global variables. However, sometimes it needs to be used. Even so, global variables should be limited to the desired environment. For example, a global variable may only be globally located in the IMPLEMentation section of the unit. Global data can be directly initialized to a value when declaring. Note that all global variables are automatically initialized, so do not initialize global variables to null values ​​such as 0, NIL or UNASSIGNED. The global variable of zero initialization is not spaced in .exe file.

Zero-initialized data is saved in the virtual data segment, and the virtual data segment is only assigned memory only when the application starts. Non-zero started his global data is occupied in .exe files. 2.5. Type 2.5.1. Sizeful write rule type identifier is a reserved word, should be written. Win32 API types are often all capitalized and follow rules such as Windows.PAS or other API units. For other variable names, the first letter should be capitalized, and the other letters are cases interlaced. Here are some examples: var myString: String; // Reserved Word WindowsHandle: HWnd; // Win32 API Type I: Integer; // In the type ID of the type ID introduced in the System unit, the floating point does not encourage the use of the REAL type, Because it is just in order to be compatible with old Pascal code. Typically, Double should be used for floating point numbers. Double can be optimized by processor, which is the standard data format defined by IEEE. You can use extend when needed than the range provided by Double. Extend is the type of Intel, Java does not support. When the physical byte number of floating point variables is important (possibly written in other languages), Single should be used. Do not directly compare the size of the two floating point numbers because the comparison results are not necessarily correct due to the error in accuracy. 2.5.3. Enumeration enumeration type name must represent the purpose of enumeration. The name is plus T character as a prefix before the name, indicating that this is a data type. The prefix of the identifier list of enumeration types should contain 2-3 lowercase characters to associate each other. For example: tsongtype = (Strock, stclassical, stalternative, strb); the name of the variable instance of the enumeration type is the same as the type, but there is no prefix T, unless a more special name, such as FavoritesongTypel, FavoritesongType2, etc. unless to give a variable. 2.5.4. Variant and Olevariant are generally not recommended to use Variant and Olevariant. However, when the data type is only known in the run (often in the COM and database applications), these two types are necessary to program. When COM programming such as Automation, ActiveX control, Olevariant should be used; and for non-COM programming, Variant should be used. This is because Variant can effectively save the native string of Delphi, while Olevariant converts all strings to an OLE string and does not reference counting functions. 2.6. Construct Type 2.6.1. Array type array type name should express the use of the array. Type names must add letter T to prefix. If you want to declare a pointer to the array type, you must add letter P to prefix, and the declaration is before the type declaration. For example: Type PcycleArray = ^ TcycleArray; TcycleArray = array [1..100] OF INTEGER; actually, the variable instance of the array type is the same name, but there is no T prefix. 2.6.2. Record Type Record Type Name The use of records should be expressed. Type names must add letter T to prefix. If you want to declare a meter pointing to the type of record, you must add the letter P as a prefix, and its declaration before the type declaration.

For example: type pemployee = ^ Temployee; TemPloyee = Record EmployeEname: String; Employeeerate: Double; End; 2.7. Statement 2.7.1. If statement is in the IF / THEN / ELSE statement, the most likely executed should be put on the In the sentence, it is unlikely to put in the else. To avoid many if statements, you can use the CASE statement instead. If more than 5, don't use the IF statement. Please use a clearer way. Do not use excess parentheses in the IF statement. If there are multiple conditions to be tested in the IF statement, you should row from right to right in accordance with the computational complexity. This allows the code to make full use of the short-circuit estimation logic of the compiler. For example, if conditionl is fast than Condition2, Condition2 is fast than Condition3, if the IF statement should construct: if the statement should construct: if Conditiorl and condit2 and condition3 Then 2.7.2. CASE statement 2.7.2.1. Overview of each case in the case statement, constants should be numbered or letters Order order. The action statement of each situation should be short and usually no more than 4-5 lines of code. If the action is too complicated, the code should be placed separately in a process or function. The ELSE clause of the CASE statement is only used for default or error detection. 2.7.2.2. Format CASE statement follows other general indentation and naming rules. 2.7.3. While statement recommends not using the exit process to exit the While loop. If necessary, you should use a loop condition to exit the loop. All code initialized for the While loop should be located before the WHILE entry and not unrelated statements. 2.7.4. For statement If the number of cycles is determined, use the for statement to replace the While statement. 2.7.5. The REPEAT statement The REPEAT statement is similar to the While loop and follows the same rules. 2.7.6. With statement 2.7.6.1. Overview with statement should be careful. To avoid excessive, multiple objects or records in the WITH statement, especially in the with statement. For example: with recordl, these situations are easily confused and causing difficulties in detecting BUG. 2.7.6.2. Format The statement also follows this chapter about naming and indentation rules. 2.8. Structured exception handling 2.8.1. Overview exception handage is mainly used to correct errors and protection resources. This means that anywhere to allocate resources must be used to ensure that resources are released. However, if it is an exception to allocate / release resources in a unit's Initialization / Finalization section or an object's constructor. 2.8.2. Try ... Finally usage, each resource allocation should match the Try ... finally structure.

For example, the following code may result in an error: someclassl: = tsomeclass.create; someclass.create; try // do some code; a seclass2.free; end; the above resource allocation is: SomeClassl: = TsomeClass.create; Try SomeClass2: = TsomeClass2.create; try // do some code fin; finally someclassl.free; end; 2.8.3. Try ... Except for use If you want an exception Perform some tasks, you can use Try ... Except. Usually, it is not necessary to use Try ... Except for simply displaying an error message because the Application object can automatically do this according to the context. If you want to activate the default abnormality in the Except clause, you can trigger an exception again. 2.8.4. Try ... Except ... Else Usage does not encourage Try ... Except with else clause, because this will block all exceptions, including the exception you are not prepared. 2.9. Class 2.9.1. Name and formatted names should express the use of class. The class name is previously adding letter T, indicating it is a type. For example: Type tcustomer = class (TOBJECT); the instance name of the class is the same as the class name, but there is no prefix T. Var Customer: TCUSTOMER; Note: For the naming of components, see the Component Type Name Standard section. 2.9.2. Field 2.9.2.1. Naming and Format Class Field (Field) Name Follow the same rule as the variable, but to add a prefix F, indicating that this is a field. 2.9.2.2. Visibility All fields must be private. If you want to access fields outside the class's scope, you can be implemented by means of a Property attribute. 2.9.3. Method 2.9.3.1. Naming and Format Method Names Follow the same rules as the process and functions. 2.9.3.2. Static method When you do not want a method to be derived, a static method should be used. 2.9.3.3. Virtual Method and Dynamic Method When you want a method to be derived, the virtual method should be used. If the class method is used directly or indirectly by multiple derived classes, the dynamic method should be used. For example, a certain class contains a method of override, and there is 100 gangs, and the method should be defined as dynamic so that the overhead of memory can be reduced. 2.9.3.4. Abstract Method If a class is to create an instance, do not use the abstraction method (Abstract). The abstract method can only be used in the base class that never creates an instance. 2.9.3.5. Property Access Method All attribute access methods should be defined in the private or protective part of the class. The attribute access method follows the same rules as the process and functions. The method for reading should be added to the GET prefix, and the method used to write should add the SET prefix, and there is a parameter called Value, which is the same as the attribute type.

For example: TSomeClass = class (TObject) private FSomeField: integer; protected function GetSomeField: integer; procedure SetSomeField (Value: integer); public property SomeField: integer read GetSomeField write SetSomeField; end; 2.9.4 Properties as a private field access. , Follow the same naming rules as the field, but there is no F prefix. The property name should be noun, not the verb. The array attribute name should be a plural, and the general attribute should be a single number. 2.9.5. The use of access methods is not required, but it is recommended that you use a write access method to access properties representing the private field. 3. Document 3.1. The name of the project file project file should have a description. For example, the project name of "The Delphi4 Developer's Guide Bug Manager" is DDGBUGS.DPR, and the name of a system information program is sysinfo.dpr. 3.2. The name of the FORM file Form file should express the use of Form and have an FRM suffix. For example, the file name called About Form is AboutFRM, the file name of the main form is MAINFRM. 3.3. The name of the data module file data module file should express the function of the data module and have a DM suffix. For example, the file name of the CUSTOMERS data module is called Customersdm.dfm. 3.4. The name of the remote data module file remote data module file should express the use of the remote data module. After the name, add the RDM suffix. For example, the file name of the CUSTOMERS remote data module is called CustomersRDM.DFM. 3.5. Unit file 3.5.1. Structure of the normal unit 3.5.1.1. The name of the cell name unit should be descriptive. For example, the application's master FORM unit is called mainfrm.pas. 3.5.1.2. The USES clause of the USES clause interface section should only contain the unit required by the part. Do not include a unit name that may be automatically added by Delphi. The USES clause of the Implementation section should only contain the unit required by this section, and do not have extra units. 3.5.1.3. Interface section The interface section should only contain the type, variable, process and function of the external unit access. Moreover, these statements should be in front of the Implementation section. 3.5.1.4. The Implementation section includes the type, variable, process and function of this unit. 3.5.1.5. The IntLalization section does not take a lot of code for the unit's initialization part. Otherwise, it will cause a very slow when the application starts. 3.5.1.6. FNALIZATION section Make sure all resources allocated in the Initialization section are released. 3.5.2. The name of the FORM unit Form unit file is the same as the corresponding FORM name. For example, the unit name of About is called AboutFRM. PAS. The name of the unit file of the main form is called MainFRM. PAS. 3.5.3. The name of the data module unit data module unit file is the same as the corresponding data module name. For example, the name of the CUSTOMERS data module unit is called Customersdm.PAS. 3.5.4. The name of the universal unit universal unit should express its use. For example, the name of a utility unit is UTILITIES.PAS, which contains the unit name of the global variable called Customerglobals.PAS. Note that the unit name in a project must be unique. 3.5.5. The element unit element unit should be placed in a separate path to distinguish the unit of the definition element.

They are generally not placed under the same path as the project. The unit file name should express its content. Note that more information about component naming standards, see the Custom Element section. 3.6. File header All source files and project files should have a file header. A correct file header should include the following information: {Copyright @ Year By Authors} 4. Form and Data Module 4.1. Form4.1.1. Form4.1.1. The name of the name of the standard Form type should express the use of FORM, and to add T as The prefix, followed by the descriptive name, and finally Form. For example, the type name of About is: Taboutform = Class (TFORM); the primary form type name is: TmaimForm = Class (TFORM); Customer login Form type name is: TCUSTOMERENTRYFORM = Class (TFORM); 4.1.2. Form instance The name of the name standard Form instance is the same as the corresponding type name, but there is no prefix T. For example, the previously mentioned FORM type and the name of the form instance are: Type instance TMAINFORM MainFormTCustomERENTRYFORM CUSTOMERENTRYFORM4.1.3. Automatically created FORM unless specifically reasons, only the master Form is automatically generated. All other FORMs must be removed from the Auto-generated list of the Project | Options dialog. For further information, see the following sections. 4.1.4. Mode Form Instantiation Functions All FORM units should contain an instantiation function, used to create, set, mode display, and release Form. This function will return the pattern result returned by form. Parameters passing to this function follow the rules of "Parameter Pass". It is necessary to encapsulate this, which is for the reuse and maintenance of the code. The form of form should be removed from the unit, and is defined as a local variable in the instantiation function. Note that this requires the Form from the automatic generation list from the Project | Options dialog. For example, the following unit file demonstrates the instantiation function of GetUserData.

unit UserDatsFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TUserDataForm = class (TForm) EdtUserName: TEdit; EdtUserID: TEdit; private {Private declarations} public {Public declarations} end; function GetUserData (var AUserName: string; var AUserID: integer): word; implementation {$ R * .DFM} function GetUserData (var AUserName: string; var AUserID: integer): word; var UserDataForm: TUserDataForm; begin UserDataForm: = TUserDataForm .Create (Application); try UserDataForm.Caption: = 'Getting User Data'; Rusult: = UserDataForm.ShowModal; if (Result = mrOK) then begin AUserName: = UserDataForm.edtUserName.Text; AUserID: = StrToInt (UserDataForm.edtUserID .Text); end; finally userdataform.free; end; end; end. 4.2. Data Module 4.2.1. Data Module Name Standard Data Module Type Name The name should be expressed and to add a prefix t, followed by the descriptive name, and finally DataMadule. For example, the type name of the Customer Data Module is: TCUSTOMERDATAMODULE = Class (TDADAMODULE) ORDERDAT module Type name: TorderDataModule = Class (TDATAModule) 4.2.2. Data Module Instance Name Standard Data Module Instance The name of the instance should be with the corresponding type The name is the same, but there is no prefix T. For example, the previous data module type, instance name: Type instance TMAINFORM MainFormTCustomERENTRYFORM CUSTOMERENTRYFORM5. Package 5.1. Running period and design period running period should only contain the required units. The units of those attribute editors and component editors should be placed in the design package. The registration unit should also be placed in the design package. 5.2. File Naming Standard Pack Name Follow the following mode: iiilibvv.pkg - Design period package iiistdvv.pkg - Running the package, III represents a 3-character prefix, used to identify companies, individuals, or other things that need to be identified . The VV represents the version number of the package, which also contains the version number of Delphi. Note: LIB or STD in the package name indicates that this is a design package or running package.

For example, the package in "Delphi4 Development Daquan" is called: DDGLIB40.PKG - Design period package DDGSTD4O.PKG - Running package 6. Component 6.1. Custom components 6.1.1. Component type naming standard components Naming is similar to the name of the class, but it has three characters prefixed. These prefixes are used to identify companies, individuals, or other entities. For example, a clock component can declare this: TDDGCLOCK = Class (Tcomponent) Note that three characters as a prefix should be lowercase. 6.1.2. Component unit element unit can only contain one main component, which means that the components currently on the component palette. Other auxiliary components or objects can also be included in the same unit. 6.1.3. Registration process of registration unit elements should be removed from the component unit and placed in a separate unit. This registration unit is used to register all components, attribute editing, component editing, wizard, and more. Component registration should be carried out in the design package. Therefore, the registration unit should be included in the design period rather than the running period. It is recommended to name the registration unit: XXXREG.PAS where xxx is 3 characters prefixed to identify companies, individuals, or other entities. For example: DDGREG.PAS. 6.2. The name of the naming rule element of the component instance should have a descriptive. Delphi does not specify the default name for the component. Components should have a lowercase prefix to indicate its type, which is for easy findings in Object Inspector and Code Explorer. 6.3. The prefix of the component is the prefix of the Delphi 4 standard element.

6.3.1. Standard page prefix element mm TMainMenupm TPouupMenummi TMainMenuItempmi TPopupMenuItemlbl TLabeledt TEditmem TMemobtn TButtoncb TCheckBoxrb TRadioButtonlb TListBoxcb TComboBoxscb TScrollBargb TGroupBoxrg TRadioGrouppnl TPanelcl TCommandList6.3.2. Additional p prefix element bbtn TBitBtnsb TSpeedButtonme TMaskEditsg TStringGriddg TDrawGridimg TImageshp TShapebvl TBevelsbx TScrollBoxclb TCheckListboxspl TSplitterstx TStaticTextcht TChart6.3.3. Win32 page prefix element tbc TTabControlpgc TPageControlil TImageListre TRichEdittbr TTrackBarprb TProgressBarud TUpDownhk THotKeyani TAnimatedtp TDataTimePickertv TTreeViewlv TListViewhdr THeaderControlstb TStatusBartlb TToolBar6.3.4. System page prefix element tm TTimerpb TPaintBoxmp TMediaPlayerolec TOleContainerdd cc TDDEClientConvddci TDDEClientItemddsc TDDEServerConvddsi TDDEServerltem6.3.5. Internet page prefix element csk TClientSocketssk TServerSocketwbd TWebDispatcherpp TPageProducerqtp TQueryTableProducerdstp TDataSetTableProducernmdt TNMDayTimenec TNMEChonf TNMFingernftp TNMFtpnhttp TNMHttpnmsg TNMMsgnmsgs TNMMSGServnntp TNMNNTPnpop TNMPop3nuup TNMUUProcessorsmtp TNMSMTPnst TNMStrmnsts TNMStrmServntm TNMTimenudp TNMUdppsk TPowerSockngs TNMGeneralServerhtml THtmlurl TNMUrlsml TSimpleMail6.3.6. Data Access page prefix element ds TDataSourcetbl Tableqry Tquerysp TStoredProcedb TDatabaseBM TBATCHMO

veusql TUpdateSQL6.3.7. Data Controls page prefix element dbg TDBGriddbn TDBNavigatordbt TDBTeXtdbe TDBEditdbm TDBMemodbi TDBImagedblb TDBListBoxdbcb TDBComboBoxdbch TDBCheckBoxdbrg TDBRadioGroupdbll TDBLookupListBoxdblc TDBLookupComboBoxdbre TDBRichEditdbcg TDBCtrlGriddbch TDBChart6.3.8. Decision Cube page prefix element dcb TDecisionCubedcq TDecisionQuerydcs TDecisionSourcedcp TDecisionPivotdcg TDecisionGriddcgr TDecisionGraph6.3.9. QReport page prefix element qr TQuickRePortqrsd TQRSubDetailqrb TQRBandqrcb TQRChildBandqrg TQRGroupqrl TQRLabelqrt TQRTextqre TQRExprqrs TQRSysDataqrm TQMemoqrrt TQRRichTextqrdr TQRDBRichTextqrsh TQRShapeqri TQRimageqrdi TQRDBImageqrcr TQRCompositeReportqrp TQRPreviewqrch TQRChart6.3.10. Dialogs actual page elements are box elements packaged form form, so it follows the form naming rules. Its type has been defined by the name of the component. The name of the instance is the same as the name of the type, but there is no prefix T. Prefix element TOpenLDialog OpenDialogTSaveDialog SaveDialogTOpenPictureDialog OpenPictureDialogTSavePictureDialog SavePictureDialogTFontDialog FontDialogTColorDialog ColorDialogTPrintDialog PrintDialogTPrinterSetupDialog PrinterSetupDialogTFindDialog FindDialogTReplaceDialog ReplaceDialog6.3.11. Win3.1 page prefix element dbll TDBLookupListdblc TDBLookupCombots TTabSetol TOutlinetnb TTabledNoteBooknb TNoteBookhdr THeaderflb TFileListBoxdlb TDirectoryListBoxdcb TDriveComboBoxfcb TFilerComboBox6.3.12. Samples page prefix element gg TGaugecg TColorGridspb TSpinButtonspe TSpinEditdol TDirect

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

New Post(0)