Object Pascal programming style

zhaozj2021-02-08  245

Object Pascal Style Guide - by Charles Calvert (Object Pascal Coding Style Wizard - Tommy Tong)

SUMMARY: This article shows a standard style that formats Delphi code. Its implementation is based on the development habits of the Delphi team.

We admit that many good studios or individuals have their own and different program habits they say in this article, but we strongly recommend that you use a tool to convert your code to the Borland style code, then Submit to Borland, Project Jedi, or any other public code knowledge base. We don't want to force you to change your habits, but we adhere to all the code that works with Borland products follows the habits described herein.

Object Pascal is a beautiful design language. Strong readability is one of its advantages. The standards designed herein will enhance the readability of the object PASCAL code. They will also become standards when developers follow these simple habits present, which will benefit all Delphi developers to use unified readable code style. Efforts to perform these standards will increase the value of the developer's source code, especially in the maintenance and debug cycle.

Although we believe and praise the style of this article, we don't have to support it because it is the correct and other other errors. However, we believe that the criteria for most developers have its effects, so we still support and maintain the style. The human brain is always adapting to standards, and looking for methods familiar to quickly organizing the implications, so as to understand their meaning. It is because the criteria established by this requirement will make a large number of people to read the code as much as possible. If we feel unfamiliar in the initial use of our guidelines, then we will hold you, you will find that you have become accustomed. Or, if you like, you can also keep your own style and convert through our standards, then you can submit your code to Borland or other knowledge base.

Some text editors, like Visual Slickedit, can help you format your code in accordance with certain styles.

A free program developed by EGBERT VAN NES can be obtained in the following connection: http://www.slm.wau.nl/wkao/delforexp.html

Another commercial program for Delphi is crackerjax: http://www.kineticsoftware.com/html/products.html

----------------------------------------

1.0 Introduction This article is not an attempt to define a syntax rule for the Object Pascal language. For example: placing the title in front of the ELSE ";" is illegal; the compiler does not allow this usage. So I will not show speech rules in this article. This article is intended to define appropriate behavior habits in the language providing selection. I usually keep silence in just a control method.

1.1 Background The guidelines in this article are based on part of the Delphi source code. Delphi source code just follows these guidelines. If you find a violation of these principles, it should be these principles instead of those uncertain source code be your guidelines. However, you can use these original code as a supplement to these principles, at least it can help you get the general view of your own code. 1.2 Thanks this article, these formats are based on the work that has been completed for the Java language definition. Java has no impact on the format Object Pascal source code on rules, but the document on the Sun website is the basis of this article. In some special places, the style and format of this article are greatly inspired by "A Coding Style Guide for Java Workshop and Java Studio Programming" (coded wizards in the Java workshop and Java studio)). This article can be found at this URL: http://www.sun.com/Workshop/java/wp-coding Delphi team has made significant contributions to this article, in fact, if there is no help, this article cannot be completed. of.

2.0 Source File Object Pascal Source code is mainly divided into single source files and project files, they all follow the same habits. The Delphi project file has a .DPR extension. It is the main file of the project. Any unit file used in the project has a .sed extension. Other files, like batch files, HTML files, or DLLs can also play a role in the project, but this article only involves project files and unit files.

2.1 Source File Name Object Pascal supports long file name. If you use a few words to form a single name, then it is best to use your uppercase with your uppercase: myfile.pas. This is considered to be inserted or hunch-type uppercase. The extension should use lowercase form. Due to historical reasons, Delphi source code often uses 8: 3 naming mode, but developers do not have to turn to the Delphi group for the above rules. If you are translating a C / C header file, then the PASCAL file you translated should maintain the same main file name, extension. PAS with the C / C header file. For example: windows.h -> windows.pas. If the Pascal syntax is forced to combine several header files into a single unit file, the file name of the header file containing other header files will be the name of the new unit file. For example: Windows.h contains a WINBASE.H file, the new unit file is called Windows.PAS.

2.2 Source File Organization All Object Pascal unit files should include the following elements in order: Copyright / Identification block annotation unit name interface segments Implement part of the end symbol "end."

At least one line between each part.

Other elements should be structurally intended to be the most appropriate order. However, copyright should appear in the beginning of the file, then the unit name, then any condition definition, compiler indicator, or include the statement, then the Uses words: {************** *************************************************} {} {Borland Delphi Visual Component Library} {} {Copyright (c) 1995, 98 Inprise Corporation} {} {********************************************** *******************} Unit button;

{$ S-, W-, R-} {$ c preload}

Interface

Uses Windows, Messages, Classes, Controls, Forms, Graphics, Stdctrls, Extctrls, CommCtrl

If you put the Type segment before the Const segment, or mix them both, it is not impact.

Implementation part needs to first write the importation, then the USES sentence, then other indicators containing declarations or other indicators: Implementation

Uses Consts, Sysutils, Actnlist, Imglist;

{$ R buttons.res}

2.2.1 Copyright / Identification Block Note Each source file should begin with an annotation of version information and standard copyright cloth. Version information can be like this: {***************************************** ************} {} {widgets galore} {} {copyright (c) 1995, 98 Your company} {} {************** ************************************************

Copyright notice requires at least the following: Copyright (c) Owner copyright owner

If you are a third party for Borland development software, you can join your own name at copyright: {************************* ****************************} {} {Borland Delphi Visual Component Library} {CopyRight (C) 1995, 99 Borland International} {Created by Project Jedi} {} {*************************************************** **************} 2.2.2 Unit declares that each unit file must have a Unit declaration. Unit is a reserved word, so it needs to be lowercase. The name of the unit can be hybrid, but must be the same as the file name of the unit file. For example: Unit myunit;

Then the name of the unit file should be myUnit.pas. In the file system, it as the entry of this file.

2.2.3 USES declaration inside the unit, the USES declaration should use small USES boot. The referenced unit name is to follow the uppercase habit used when it is defined in his own unit: uses myunit;

Each unit name is separated by a comma with its neighboring unit name, and the last cell name is followed by a semicolon: Uses Windows, Sysutils, Classes, Graphics, Controls, Forms, Typinfo;

The next line of Uses starts to join the cell name and directly adding the cell name after Uses is equally correct. Uses Windows, Sysutils, Classes, Graphics, Controls, Forms, Typinfo;

You can format your cell name list, you can restrict the wrap on 80 characters, or each cell name.

2.2.4 Class and Interface Definitions The definition of classes begins with two spaces, then a prefix "T". The prefix is ​​capitalized, and each embedded word should be larger. Do not use tabs "tab" in the Object Pascal source code. Example: TMYCLASS picks up a space after the identifier, then the equal sign, then the class word, Class should lower-how: TMYCLASS = Class If your class is inherited from the ancestor, you need to add the left and right parentheses: The TMYCLASS = Class (TOBJECT) range indicator two spaces from the page, and appears in the order in the following: TMYCLASS = CLSS (TOBJECT) private protect public public public published end;

Data is usually only declared in the Private section, and their identifiers start with "F". All such statements from the four blank spaces: TMyClass = class (TObject) private FMyDate: Integer; function GetDate: Integer; procedure SetData (Value: Integer); public published property MyData: Integer read GetData write SetData; end; Interface Follow the same rules as the same type, except that you should ignore the range indicator and private data, and use the Interface word instead of the Class word.

Naming habits In addition to reserving words and indicators, all PASCAL identifiers should use hump format, that is, each identifier begins with uppercase, the first letter of embedded words should also be capitalized, only the first alphabetical abbreviation The same is true. MyIdentifier myftpclass

The main exception of this rule is the case of header file translation, and the naming habits in the original file should be followed. For example: wm_lbuttondown, don't write to WM_LButtondown.

In addition to the header file translation, do not use underscore segmentation words. Class names should be nouns or noun phrases. The name of the interface or class depends on the obvious purpose of the interface, the purpose.

Good name: addressform, arrayindexoutofboundsexception is poor name: managelight download // use verb phrase delphi_is_new_to_me // use underscore

3.1 Unit Naming See Unit Declaration

3.2 Class / Interface Naming See Class / Interface Declaration

3.3 Domain / field Naming Use the hump format. Start with uppercase "F" and declare all data, use attributes or acquisitors and installers (Setter) to provide public access operations. For example: use the name getSomething to name a function that returns the internal domain / field value, uses setsomething to name a process of setting up domain / field values. Don't use uppercase in the Const section unless the need for the header translation. Delphi is developed in California, all of us prevents the use of marks unless the need for header file translation. Correct: FMYSTRING: String; incorrect: lpstrmystring: String;

Of course, the Hungarian nomenclature is retained in the enumeration type: tbitbtnkind = (BKCUSTOM, BKOK, BKCANCANCANCENCEL, BKHELP, BKYES, BKNO, BKCLOSE, BKABORT, BKRETRY, BKIGNORE, BKALL);

In this case character BK is inserted into each element of this enumeration type. BK means ButtonKind.

When considering naming habits, avoid the name of the single character, except for temporary variables and cyclic variables. Avoid using the "L" variable because it and "1" are difficult to distinguish between the printer or on the display.

3.4 Method Naming Method Named also uses a hump format. Method Naming habits are the same as a very quantity of naming methods, but you can distinguish them from the context. Method Naming should force usage verbs or verb phrases. For example: // Good method naming: showstatus, drawcircle, addLayoutComponent / poker Naming: MouseButton // Noun phrase, no description function Drawcircle // With lowercase letters start add_layout_component // Using Underline // The following method is not enough clear. It is starting to run a service (better: startserver) or determine if a service is running (better: isserverrunning)? Serverrunning // verb phrases, but not orders

A method for obtaining or setting some class properties should be called getProperty or setProperty, and Property represents the name of the attribute. For example: GetHeight, SetHeight

The method of the Boolean properties of a test class should be named isvisible, visible represents the name of the property. For example: IsResizable, isvisible

3.5 Local Variable Naming In addition to not using "F", the naming rules of local variables are the same as the naming rules of the domain / field. See Section 3.3.

3.6 Reserved Word retention word and indicator should be lowercase. This is sometimes chaotic. For example: Integer is an identifier and appears in the case of the case. And String reserves all lowercase.

3.7 Type Declaration All Type Name State begins with the letter T, next to the name of the class.

4.0 Blank Usage 4.1 Blank line blank row can be enhanced by grouping logic-related code segments to increase readability. A blank line can also be used in the following places: After the copyright note block, the package declaration (IMPORT). Class declarations. Method declaration between.

4.2 Space Object Pascal is a very clear language. Usually, you don't need to add a lot of spaces to your code. Several of the following is how to use spaces: 4.2.2 Should not use spaces: between method name and left brackets; before or after. (DOT) Operators; between one yuan operator and its operand Between a type and the expression that is forced by it; before the left brackets and the right brackets; before the left brackets and the right parentheses; in a title; for example: // correct usage: function TMYCLASS. MyPointer: = @myRecord; myclass: = tmyclass (myinteger); Myinteger: = MyintegeraRray [5]; // Error usage: function tmyclass.myfunc (var value: integer); mypointer: = @ MyRecord; myclass: = tmyclass (mypointer); Myinteger: = MyintegeraRray [5]; 4.3 Adjustment You should always indent the two spaces for all indentations. In other words, the first layer is indented into two spaces, the second layer is indented into four spaces, and the third layer is indented into six spaces ... Do not use tab Tab. Of course, there is still a small amount of exception. Keep a word Unit, Uses, Type, Interface, Implement, Initialization, and Finalization are always top. The last End identifier of the unit is also a top. In project files, Program and Master Begin, End are also top. Inside the primary begin..nd block, you need to indent at least two spaces.

4.4 Continued lines should be limited to 80 columns. The rows of more than 80 columns should be divided into multiple consecutive rows. All subsequent lines should be arranged after the first line of the declaration and indent the spaces of the two characters. For example: // correct: function CreateWindowEx (dwExStyle: DWORD; lpClassName: PChar; lpWindowName: PChar; dwStyle: DWORD; X, Y, nWidth, nHeight: Integer; hWndParent: HWND; hMenu: HMENU; hInstance: HINST; lpParam: Pointer : Hwnd; stdcall;

IF ((x = y) or (y = x) or (= p) or (f = j) THEN BEGIN S: = J;

Do not go online between parameters and its type unless the list is separated by a comma, then go forward before the last parameter, this type name begins at the next line. There should be a space between the colon and its variables, while there is a space between the colon and type name. // Correct: Procedure Foo (Param2: Integer); // Error: Procedure Foo (Param: Integer; Param2: Integer);

A subsequent line should not start with a binary operator. Avoid cutting a row in places usually do not appear, such as between the method name and its left brackets, or between a group name and its left brackets. If you have to cut the line in the above case, then you should go back to the left bracket or left brackets. Don't put the beGin in the same line of other code. For example: // Error: While (longexpression1 or longexpression2) do beg // dosomething // dosomethingelse;

// Correct While (LONGEXPRESSION1 or LONGEXPRESSION2) Do Begin // DOSMETHING / / DOSMETHINGELSE; END;

IF (LONGEXPRESSIONG1) or (LONGEXPRESSION2) or

5.0 Note Object Pascal Language Supports two annotations: blocks and separate comments. The following is some of the Note for Note: • Place the annotation at the top of the unit to interpret the use of the unit is beneficial • Place the annotation in front of the category declaration is beneficial • Setting the annotation in the method declaration is beneficial · Avoid statement meaningful notes i : = i 1; // add one to i

· Remember that the inclusion that is easy to misunderstood is more harmful than not comment. · Avoid adding information that looks to failure in the comments • Avoid embed an asterisk or other typographic symbols, zero annotations in the border of the comment, that is, you need to change or delete a comment, you should add " ???: "Mark, so easy to find. In terms of concept, all zero annotations should be deleted before the program is released. // ???: Change this to call sort means; fixed list.mys;

5.1 Note Object Pascal supports two types of block note. The most commonly used annotated comments enclosed in the parentheses {}. The Delphi group keeps the annotation as much as possible and simple. For example: You should avoid using an asterisk in your comment to create a pattern or row. Instead, use spaces to separate your comments, just like you do in the word processing document. The words in your comments should begin in the same line of the first curly bracket, just like the following from DSGnintf.pas:

{TPROPERTYEDITOR

Edits a property of a component, or list of components, selected into the Object Inspector. The property editor is created based on the type of the property being edited as determined by the types registered by ...

ETC ...

GetXxxValue Gets the value of the first property in the Properties property. Calls the appropriate TProperty GetXxxValue method to retrieve the value.SetXxxValue Sets the value of all the properties in the Properties property. Calls the appropriate TProperty SetXxxxValue methods to set the value.}

Block comments are usually used in copyright comments. Also used to comment out some of the code rows.

Block notebooks for explaining methods should be interviewed in front of the declaration of the method. For example: // Correct

{TMYOBJECT.MYMETHOD

This routine allows you to execute code.}

Procedure TmyObject.mymethod; begin end;

// incorrect

Procedure TmyObject.mymethod; {********************************************************************** ********** TMYOBJECT.MYMETHOD

THIS ROUTINE ALLOWS You to Execute Code. **************************************************** *************} begin end;

The second block comment contains two characters, parentheses, and asteromers: (* *). This is sometimes referred to as a comment. These comments are generally useful when code development, and its main benefits are to allow nested annotations, and the comments are less than two layers. Object Pascal does not support the same type of annotation nested, so there is only one layer of nested: the curb brackets are in the brackets, or the squid is in the lacerans. As long as you don't nearen them, other types of standard Pascal annotations in this type of comment will be ignored. Therefore, you can use the syntax to comment a large piece of code that has both code and comment:

(* Procedure TForm1.Button1Click (Sender: TObject); begin DoThis; // Start the process DoThat; // Continue iteration {We need a way to report errors here, perhaps using a try finally block ???} CallMoreCode; // Finalize the process end; *)

In this example, the entire Button1Click method is commented, including any sub-comment therein.

5.2 Untrial Note Untrial Note Composed by the text of the annotation / / and its boot, there is a space between the text and the comment. The single line comment is in the same line, and it is necessary to have the same indented level as the code. You can use multiple single-way comments to form a big comment. There is a blank line before a single line comment or an comment group, unless it is the first line of a block. If comments are used in several statements, then follow the comments and comment groups to follow an empty line. If the comment only explains the row of declarations behind it, you don't have to follow a blank line. For example: // Open the database table1.open;

Untrial comments can also be followed by the code declaration they explain. This type of comment is sometimes referenced to track comments. There is at least one space between them and the code. If there are multiple tracking comments that appear simultaneously in a code block, then these comments need to be aligned. For example, if (not isvisible) kil1, // Nothing to do inc; // reserve space for Null Terminator To avoid tracking annotations for each row executable code. The use of comments between the BEGIN..end block of a method or function, even make it empty, the best in the usual situation. Long annotations can appear in block note before the definition of the function.

Organizations for organizational categories of class 6.1 should follow the following sequence: Domain / field declaration, method declarations, attribute definition domain / fields, properties, and methods should be arranged by alphabetically indexing in their name.

6.1.1 Access Level In addition to the code generated by the IDE, the scope indicator of the class should be in the following order: · Private declaration · Protect declaration · Public declaration · Published declaration in Object Pascal, class members have four access level: release Open, protected and private - arranged in sequence of reducing capacity. The default access level is Published. Typically, a member should be given the most suitable minimum access level. For example, only members of the same unit can be declared as private in the same unit. At the same time, members who declare that low access level also give the compiler to improve optimization opportunities. Of course, on the other hand, there is difficult to use low access levels. If there is reason to think that a class will be subcatenated at some time, those who need to be extended to be extended to be protected as protected, and attributes for accessing private data can also provide this protection. You should prohibit public access to the data. Data is typically declared in the Private section, any public access to him should be operated by getxxx, setxxx methods, or attributes. 6.1.8 Constructive Declaration The method needs to be arranged in alphabetically index. Place the constructor and the destructive function in the start of the public paragraph or in the alphabet index arrangement. If there are multiple constructor or you use multiple identical names, then it should be arranged according to the mediate table, and the parameters are small in front of the parameter. This means that if there is a constructor without parameters, then it must appear in the first one. To maintain the best compatibility with C Builder, the uniqueness of the parameter list of constructor should be guaranteed. C is not called according to the name of the constructor, so the unique way to distinguish multiple constructor is through its parameter list.

6.2 Method Declaration If possible, the method declares that it should appear on a single line. For example: Examples:

// Broken Line is aligned two spaces in from left. Procedure ImageUpdate (Image IMG, Infoflags: Integer, x: Integer, Y: Integer, W: Integer, H: Integer

7.0 Declaration of Interface Interface The Declaration of the Class has the same form: InterfaceName = Interface ([Inherited Interface]) interfaceBody End;

The interface declaration should be indented, the interface body is indented, and the end is ended into two grids. There is no domain / field in the interface statement. But attributes can appear. All interface methods are born to open and abstract, and do not include such keywords in the interface declaration. Unless otherwise considerations, the status of the interface is similar to the same style. 7.1 The organization of the interface body tissue interface can be in the following order: • Interface method declarations • Interface attribute declaration interface methods and attributes declarations and classes have the same style.

8.0 Declaration The statement is a row or a few lines of code ending the title. Single statement has only one title, there are multiple seals in the composite statement. // This is a single statement: A: = B;

// This is a composite statement: Begin B: = C; A: = B; END;

8.0.1 Single Statement If you need to put a single declaration, you need to refill the two lines to the previous line. //, for example: myValue: = myValue (someverylongStatement / OtherLongStatement);

8.1.1 Assignment and expression declares that there is a declaration in each row. For example: A: = B C; INC (count); // error A: = B C; // correct inc (count); // correct

8.1.2 Local variable declares that local variables also use hump formats, do not use guidance "f", which is preserved for class declarations. For example: Var mydata: integer; mystring: string;

You can declare multiple types of variables in the same line: Var Arraysize, ArrayCount: Integer;

This kind of statement is not advocated in class declarations.

8.1.3 Array declaration usually places a space after the left brackets and the right brackets: Type Tmyarray = array [0..100] OF CHAR;

8.2.3 If statement If statement occurs at least in the form of two lines: for example: // error: if a

If it is a composite IF statement, you should have a new row each separator: // Error: if a

The following minority changes can be adopted: // Correct IF Condition Then Begin Dothis; ELSE BEGIN DOTHAT;

// Correct IF Condition Then Begin Dothis; Else Dosomething;

// Correct IF Condition Then Begin Dothis; END ELSE DOSOEMTHING;

// The following method may not be careful, but it is commendable: if Condition Then Dothis else Dothat;

8.2.4 for statement example: // incorrect for i: = 0 to 10 do begin dosomething; dosomethingelse; end; // CORRECT for i: = 0 to 10 do begin dosomething; dosomethingelse;

8.2.5 While Statement EXAMPLE: // IncorRect While X

// Correct While x

8.2.6 Repeat Until statement example EXAMPLE: // CORRECT REPEAT X: = J; J: = UpdateValue; Until J> 25;

8.2.7 Case statement example control.Align of alleft, alnone: newrange: = max (newrange, position); alright: inc (Align Margin, Control.Width);

// CORRECT CASE X of

CSSTART: Begin J: = UpdateValue;

CSBEGIN: X: = J;

Cstimeout: Begin J: = X; x: = UpdateValue;

END;

// CORRECT case ScrollCode of SB_LINEUP, SB_LINEDOWN: begin Incr: = FIncrement div FLineDiv; FinalIncr: = FIncrement mod FLineDiv; Count: = FLineDiv; end; SB_PAGEUP, SB_PAGEDOWN: begin Incr: = FPageIncrement; FinalIncr: = Incr mod FPageDiv; Incr : = INCR DIV FPAGEDIV; Count: = fpagediv; end; else count: = 0; InCr: = 0; FinalInCr: = 0;

8.2.8 try statement Example: // Correct try try EnumThreadWindows (CurrentThreadID, @Disable, 0); Result: = TaskWindowList; except EnableTaskWindows (TaskWindowList); raise; end; finally TaskWindowList: = SaveWindowList; TaskActiveWindow: = SaveActiveWindow; end;

-------------------------------------------------- ---------------------------- Add or View Comments on this article

Article ID: 10280 Publish Date: January 01, 1999 Last Modified: October 01, 1999

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

New Post(0)