Document directory
- Warning (warnings)
- Optimization suggestion)
- Memory recommendation (memory)
- Code reduction)
- Convention Compliance)
- Case Insensitive suggestion (inconsistent case)
Overview
No matter how different the writing style of each person in the development team is, how can someone else quickly understand their own code and maintain your code. Avoid unnecessary simple errors as much as possible, and make certain constraints for coding.
If you say that I do not need to be standardized, it is not. Your personal code style shows your actual capabilities. It is as messy as writing an article. It is useless for others to read wonderful stories. In the future, your own maintenance will be too big.
Therefore, it is necessary to have a simple code writing constraint, which not only improves readability but also improves code quality.
1. Create an analysis project
After the software is opened, a wizard interface is displayed (disabled by default, which can be opened through run wizard under the File menu). Select the project to be analyzed on the project selection interface (as shown in)
(Figure 1)
Select the project and next, select the Delphi version. On the analysis settings page, select (main file and used units) instead of the DFM file, path, and condition settings page, you can leave all the options unselected (these can be adjusted later). After confirming the options, you will be prompted to save them. You can choose to save (or not save them, the tool is in the analysis phase (wait a moment). After analysis, an analysis report is generated, as shown in)
(Figure 2)
You can also directly create a project (new project or toolbar under the File menu) after entering the interface, and then click "run" in the analysis.
Analysis project file (. DPR) does not need to be compiled, you can create only the units to be analyzed according to the analysis needs, it is best to have a configuration file with the same name as the project (. DOF ).
2. Set project options
After opening an existing project or creating a new project, select the project properties (or open the project in the new project mode)
Note the following:
A) Target version. This option is selected based on the actual situation (you are not sure what impact the analysis will have)
B) Include files must exist (include files must exist). You can leave this option unselected (especially when some directories are excluded, selecting this option will cause analysis errors and interruptions)
C) use the Project Settings (use Delphi project options if found). If this option is selected for full engineering analysis, the analysis tool uses the search path in the project, there are many analysis units.
D) Delphi environment path (append Delphi library path and browsing path) this option is not recommended.
E) when the exclude search path is set, the analysis tool does not analyze the units in the exclusion path, because the project often carries the control of the 3rd-party, in this case, excluding these control directories and subdirectories will reduce unnecessary analysis (note that the excluded paths may not support relative paths. It is best to use absolute paths or directly set them through the wizard ).
3. Explanation of the Analysis Report
The tool has many analysis reports. Based on a period of use and analysis, the following analysis items are of great significance:
Warnings (warning ):
Ambiguous unit references (important)
Interfaces passed as parameters without "const" Directive (important)
Constructors/Destructors without callto inherited (important)
Function result not set (important)
Interfaced identifiers that are used, but not outside of Unit (General)
Interfaced Class Identifiers that are public/published, but not used outside of Unit (General)
Dangerous exit-statements (General)
Empty finally-block (General)
Possible bad object creation (General)
Ambiguous references in with-blocks (General)
Optimization (optimization ):
Missing "const" for unmodified string parameter (important)
Local subprograms with references to outer local variables (General)
Memory (memory ):
Local objects with unprotected cballs to free (General)
Unbalanced create/free (General)
Code reduction ction ):
Local identifiers that are set and referenced once (General)
Local long strings that are initialized to empty string (General)
Boolean assignment can be shortened (General)
Convention Compliance (conventions)
Local identifiers that "shadow" outer scope Identifiers (General)
Inconsistent case (case insensitive)
Inconsistent case for same identifier (General)
The following is a brief description of these concerns for ease of understanding.
Warning (warnings) important considerations
A) ambiguous reference relationship (ambiguous unit references)
This prompt indicates that the constants, functions, and processes used have duplicate names, which need to be analyzed and eliminated as much as possible.
B) const declaration is not added to interface type parameters (interfaces passed as parameters without "const" Directive)
function Save(ADB: IBaseDBIntf): Boolean; virtual;
When the API is passed as a parameter without a const declaration, the compiler adds _ addref to the call and _ release to the call. This reduces the efficiency when the call is completed frequently.
C) Constructors/Destructors without callto inherited)
If the class inherits the parent class, calling without inheritance during deconstruct may cause the parent class to not be initialized; calling without inheritance during destructor may cause memory leakage. This also includes (Destructors without override is not declared to overwrite ).
D) The function does not set the return value (function result not set)
function TdlgInputHuanSuanLv.ActOkNotify: Boolean;begin DoOk;end;
In this case, a warning is usually prompted during Delphi compilation. If the function is not set to return values, unexpected results may occur.
General considerations
A) The external definition (including declarations such as classes and functions) is used, but only in this unit (interfaced identifiers that are used, but not outside of Unit)
Simple Example: function booltoint
function BoolToInt(ABoolValue: Boolean): Integer;implementation{$R *.dfm}function BoolToInt(ABoolValue: Boolean): Integer;begin Result := Integer(ABoolValue);end;procedure TForm1.Button2Click(Sender: TObject);begin ShowMessage(IntToStr(BoolToInt(False)));end;
This prompt lists unnecessary functions or classes that may be categorized and designed after analysis.
B) Public attributes and methods of the published class are used only in this unit (interfaced Class Identifiers that are public/published, but not used outside of unit)
This prompt can be used to simplify the attributes and methods of public access.
C) Dangerous exit (Dangerous exit-statements)
In a process or function, if there is exit at the beginning, this information will be prompted. There are two common cases: first, this process is not used. We recommend that you delete this process; the other is the code added during debugging, but you forgot to delete it. You need to confirm and verify the code.
D) Empty force execution module (empty finally-block)
Try… with this prompt... The finally structure can be deleted to improve code efficiency.
E) It may be the process of creating an error class (possible bad object creation)
Procedure proc; var BMP: tbitmap; begin BMP. Create; // error end; Procedure proc2; begin tnode. Create (parent); // Memory leakage end;
Code with such a prompt may cause errors or memory leaks.
F) dangerous block declaration references (ambiguous references in with-blocks)
procedure TForm1.Button1Click(Sender: TObject);begin with Button1 do begin Caption := 'test'; end;end;
This kind of prompt usually occurs when the block-defined class instance and the class to which the process belongs have the same name attribute or process (such as code Caption), which often leads to problems in complicated logic.
Optimization suggestion (optimization) important considerations
A) The unmodified string parameter is not declared as const (missing "const" for unmodified string parameter)
function LoadSQL(ACondition: string; AOnlyStruct: Boolean = False):
Because the string has reference count, add the const before you explicitly know the string parameters that do not need to be modified to improve efficiency. Similar parameters include record, array, and interface.
General considerations
A) Sub-processes use out-of-process variables (local subprograms with references to outer local variables)
procedure TSelectTextHelper.InitFields(AFields: TSerializableFields; AItem: TSerializeItem);var i: Integer; aField: TSerializableField; procedure InnerAddField(AIdx: Integer); begin aField := TSerializableField(AFields.Append); aField.FieldName := aField.FieldItem.ClassFieldName; aField.DataType := TypeKindToFieldType(aField.FieldItem.DataType); end;begin AFields.Clear; if AItem <> nil then begin i := AItem.ObjFieldsMap.IndexByName(AItem.KeyField); InnerAddField(i); end;end;
As shown in the code above, the sub-process uses the outside afield, which should be avoided as much as possible (especially the code segment that affects efficiency). We recommend that the sub-process be placed before the variable declaration as much as possible.
Memory recommendations (memory)
A) objects in the process are not released within the protection structure (local objects with unprotected cballs to free)
VaR alist: tlist; begin alist: = tlist. Create; // omitting the logical process alist. Free;
When the object release process does not protect the structure, if an exception is thrown or exited before the release, it will cause memory leakage. We recommend that you try to use try... Finall structure.
B) asymmetric create and release (unbalanced create/free)
procedure LocalProc;var Obj: TMyClass;begin Obj := TmyClass.Create; Obj.DoSomething;end;
Asymmetric release often results in Memory leakage. However, the analysis tool does not judge enough of some list and global objects, leading to many false positives. In addition, the following situations are not recommended. It is best to pass the returned object as a parameter to avoid leakage caused by negligence.
Function tform1.getlist: tstringlist; begin; // omitting the logical result: = tstringlist. Create; end; // we recommend that you change it to procedure tform1.getlist (alist: tstringlist); begin; // omitting the logical end;
Code reduction
A) the local variables are used only once (local identifiers that are set and referenced once)
VaR aData: tsearchresult_data; begin if fdatalist <> nil then begin aData: = tsearchresult_data (fdatalist. items [aindex]); if not aData. valid then value: = cst_invalid_price; end; // can be simplified to begin if fdatalist <> nil then begin if not tsearchresult_data (fdatalist. items [aindex]). valid then value: = cst_invalid_price; end;
Variables that are used only once in a loop can be streamlined. For example, this case requires specific analysis. In many cases, the analysis report prompts are incorrect. There are also local identifiers that possibly are set and referenced once, which are not listed here.
B) during the process, the string variable Initialization is null (Local long strings that are initialized to empty string)
VaR S: string; begin S: = ''; // The logic is omitted.
As shown in the preceding example, setting s to NULL is unnecessary and the compiler has automatically initialized.
C) Boolean value assignment can be simplified (Boolean assignment can be shortened)
If checkedcount> 0 then newstate: = true else newstate: = false; // it can be reduced to newstate: = checkedcount> 0;
This type of prompt is often the code that uses conditional judgment and then value assignment. This type of code can be optimized or concerned (unneeded Boolean comparisons ).
Convention Compliance
A) Local identifiers that "shadow" outer scope identifiers
Procedure tfrmmessagedlg. showbutton (flags, timecount: integer); function getbuttons (flags: integer): tmsgdlgbuttons; begin; // omitting logical end;
This usually happens in a sub-process. As shown in the code above, we recommend that you do not duplicate the names, which may lead to a reduction in the number of transactions.
Case Insensitive suggestion (inconsistent case)
A) The same definition is case insensitive inconsistent case for same identifier
procedure DoSaveEvent(ATotal, ACur: Integer); begin if Assigned(FSaveEvent) then FSaveEvent(aTotal, aCur); end;
As shown in the code above, the parameter bits are in upper case and in lower case when used. This does not comply with the encoding specifications. We recommend that you pay attention to this prompt to make the code more standard.
4. Conclusion
It is necessary to unify code specifications in team cooperation. Improve code quality, improve code readability, etc. The above only lists part of the content, the Analysis ReportGeneralThere are still many good suggestions under the Branch, which can be applied in our daily work. In addition, although the help documentation of this tool is simple, the meanings of the suggestions are explained. You may wish to read it.