Specifications recommended by Delphi Programming 1---Indentation, usage of various statements

Source: Internet
Author: User
Tags case statement uppercase letter

In programming, especially in a large team, it is extremely important to follow a unified programming specification. Develop a source code writing standard for all developers and a naming standard for programs and files so that they are programmed in a consistent format so that code written by each programmer can be understood by others, reducing the cost of program maintenance and handover.

Here first only about the Delphi language programming specifications, temporarily skip files, project naming ...

1.1. About Indentation

Indentation provides a clearer display of the logical structure of the source code, with two space characters, and cannot use tabs (that is, tab characters). This is because the width of the tabs with different source editing tools and different settings, the effect of the display is not the same, if the space and tab key Mix, it is likely to show a chaotic structure

1.2.begin...end statements

The BEGIN statement should have a separate line, for example

Incorrect use of

For i:=0 to ten do begin

The right usage

For I:=0 to ten Dobegin

This rule has a special case when begin is part of the else statement, such as

If Somestatement thenbegin ...    end;else someotherstatement begin ...    end;

Note: The end statement is always a single row, and when begin is not part of the Else statement, the corresponding End statement is the same as the indent of the BEGIN statement

1.3. Casing Rules

Although Delphi is not case-sensitive, the use of uniform casing rules is extremely beneficial, allowing you to look at the code without being overwhelmed

Type identifiers are reserved words and should all be lowercase. The Win32 API type is often capitalized and follows rules such as Windows.pas or other API units about a particular type name. For the mournfully variable name, the first letter should be uppercase, the other letters are case-insensitive, example

var    smystring:string;    Reserved words, all lowercase    hwindowshandle:hwnd;    Win32 API type, all caps    I:integer;    Type identity referenced in the system unit, specific type name

1.4. Floating-point type

Typically, a double is used for floating-point numbers, and the real type is discouraged because it is reserved for compatibility with old Pascal code. Double can be optimized by the processor and is the standard data format defined by IEEE. You can use extend when you need a larger range than the double provides.

1.5.Variant and Olevariant

Variant and olevariant are not generally recommended. However, these two types are necessary for programming when the data type is known only at run time (often in programs that are used in COM and database applications). When you make COM programming such as automated ActiveX controls, you should use olevariant, whereas for non-COM programming you should use a Variant. This is because the variant effectively preserves the Delphi's native string, and olevariant converts all strings to an OLE string (that is, the Widechar string) without the reference count feature.

1.6. Local Variables

Local variables are used inside the procedure, and variables should be initialized immediately at the entrance of the procedure, if necessary. Local ansistring types of variables are automatically initialized to empty strings, local interfaces and dispinterface types of variables are automatically initialized to nil, local variant and olevariant types of variables are automatically initialized to unassigned.

1.7. Global Variables

It is generally discouraged to use global variables. However, sometimes it needs to be used. Even so, you should limit the global variables to the environment you need. For example, a global variable may be global only in the implementation part of the cell.

If the global data is to be used by many units, it should be moved to a common unit that is used by all objects. Global data can be initialized directly to a value when declared. Note that all global variables are automatically initialized for 0, so do not initialize the global variables to null values such as 0, nil, or unassigned. 0 initializes the global variables in the. EXE file does not occupy space. 0 The initialized data is saved in the virtual data segment, and the virtual data segment allocates memory only when the application starts. Global data that is not 0 initialized is in the. EXE file occupies space .

1.8.if statements

In the If/then/else statement, the most likely scenario should be placed in the then clause, which is unlikely to be placed in the ELSE clause. To avoid many if statements, you can use case statements instead. If more than level 5, do not use the IF statement. Instead, use a clearer approach. Do not use extra parentheses in the IF statement.

If you have more than one condition in the IF statement to test, you should rank from right to left according to the complexity of the calculation. This allows the code to take full advantage of the compiler's short-circuit estimation logic. For example, if Condition1 is faster than Condition2 ,Condition2 than Condition3 Fast

1.9.case statements

the constants in each case statement should be in the order of numbers or letters. The action statement for each case should be short and usually no more than the 4-5 line code. If the action is too complex, you should place the code in a single procedure or function. The ELSE clause of the case statement is used only for default or error detection.

1.10.while statements

We recommend that you do not use the exit procedure to exit the while loop . If necessary, you should use a loop condition to exit the loop. All code that initializes the while loop should be in front of the while portal and not be separated by unrelated statements. The ancillary work of any business should be carried out immediately after the cycle.

1.11.for statements

If the number of loops is deterministic, you should replace the while statement with a for

1.12.repeat statement.

The repeat statement is similar to the while statement and follows the same rules

1.13.with statements

The WITH statement should be used with caution, to avoid overuse with statements, especially with multiple objects or records in the WITH statement, examples

With Record1, Record2 dobegin ...    . end;

These situations can easily confuse programmers and cause difficulties in debugging

1.14. Procedures and functions

The procedure name or function name should start with an uppercase letter, with the first letter of each word capitalized, for example

Procedure Thisisapoorlyformattedroutinename;    The wrong wording makes it difficult to see procedure thisisbetterprocedure;    This is easier to read

Whenever possible, the same type of parameters should be merged together, which can reduce the length of the code, for example:

Procedure Foo (Param1:imteger; Param2:imteger; Param3:imteger; param4:string);  Not recommended usage procedure Foo (param1,param2,param3:imteger; param4:string); Recommended usage

the order of the parameters is mainly to consider the call rules of the Register, the most commonly used parameters should be used as the first parameter, according to the frequency of use from left to right, input parameters before the output parameters, the scope of the parameter should be small in the range of parameters. There are exceptions, such as: During event handling, the sender parameter of the TObject type is often the first parameter to be passed

1.15. Constant parameters

To make a parameter of a record, array, short string, or interface type incapable of being modified by a procedure, the formal parameter should be marked with a const. In this way, the compiler generates the code in the most efficient manner, guaranteeing that the passed parameters are immutable.

if other types of parameters do not want to be modified by the procedure, you can also mark the Const. Although this has no effect on efficiency, this brings more information to the caller of the process.

1.16. Structural exception handling

Exception handling is primarily used to correct errors and protect resources. This means that wherever resources are allocated, try...finally must be used to ensure that resources are released. However, the allocation/deallocation of resources is an exception if the initial/end part of the cell or the constructor/destructor of the object

The use of 1.17.try...finally

Where possible, each resource should match the try...finally structure, such as the wrong code

SomeClass1: = tsomeclass.create; SomeClass2: = tsomeclass.create;  When this statement is faulted, SomeClass1 cannot release the try {do some code}finally someclass1.free; Someclass2.free;end;

The correct code

SomeClass1: = tsomeclass.create;try SomeClass2: = tsomeclass.create;  Try {Do some code} finally someclass2.free; End;finally Someclass1.free;end;

But if there are many classes that need to be created at the same time, this scenario is cumbersome, and the following security scenarios are recommended

SomeClass1: = nil;  SomeClass2: = nil;try SomeClass1: = tsomeclass.create;  SomeClass2: = tsomeclass.create;  {Do some code}finally freeandnil (SOMECLASS1); Freeandnil (SomeClass2); end;

The use of 1.18.try...except

If you want to perform some tasks when an exception occurs, you can use Try...except. In general, it is not necessary to use try...except to simply display an error message because the Application object can do this automatically based on the context. If you want to activate the default exception handling in the clause, you can trigger the exception again.

Note: In general, the original error message usually needs to be shielded from being seen by the user, instead of being converted to our custom, more understandable description to the customer. But the original error message can not be directly discarded, otherwise, will give us to troubleshoot problems brought greater difficulties, it is generally necessary to record more detailed error scene information and raw error information, in case of troubleshooting problems. If it is clear that you want to block a class of exceptions, you can not log the error message, but this situation is used with caution. For example: improper usage:

Scount: = ' aaaa '; try   iCount: = Strtoint (Scount); except   {What is the conversion error data? Why is it wrong? I don't know, so it's a big   problem for troubleshooting. ShowMessage (' Scount conversion type failed! '); End

The right usage

Scount: = ' aaaa '; try   iCount: = Strtoint (Scount); except on  e:exception do  begin     Writelog (' Scount ( The current value is:%s) the conversion type failed! The error message is:%s ', Scount, e.message);    ShowMessage (' Scount conversion type failed! ');  End;end;

Specifications recommended by Delphi Programming 1---Indentation, usage of various statements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.