Writing code is an art. With Delphi, anyone can easily develop some kind of software and accomplish certain tasks. And the perfect code can only be written by a true master. In addition to the correct indentation, capitalization, naming rules, always keep in mind Einstein's famous sayings-simplicity is beauty. Here are the five code questions that may be made by beginners and even some veteran birds.
Advice one
The assignment operation of a Boolean variable should be straightforward. For example, in a if/then/else statement, the IF clause assigns a Boolean variable to true, while the ELSE clause assigns it to false. The following code is bad:
If If_love_delphi Then
Result:=true
Else
Result:=false;
And this is better to write:
Result:= If_love_delphi;
Advice two
Avoid using nested if/then/if statements instead of with and. The following code is too verbose:
If If_love_delphi Then
If If_love_linux Then
Trykylix (now);
It should be written like this:
If If_love_delphi and If_love_linux then
Trykylix (now);
Do not worry about the subsequent judgment statements will be executed in advance. Project| options| compiler| Syntax options| The complete Boolean eval option is usually turned off (unless you select this item), which ensures that the execution order is not reversed.
Combine the top two tips if you have a code like this:
If If_love_delphi Then
If If_love_linux Then
Result:=true;
You can change it to:
result:= If_love_delphi and If_love_linux;
Simply put, if the result is determined by a condition, then a statement such as Result:=true or result:=false is superfluous. You can assign values to Boolean variables when they are initialized. But there is no need to initialize a Boolean variable to False--delphi when the variable is created, it has been assigned the position false. Similar scenarios include:
The Boolean property of the Object (Boolean), which is automatically initialized to False (0);
Integer variable (integer), automatically initialized to 0;
String, which is automatically initialized to an empty string.
Advice three
When judging the value of a Boolean variable, you do not need to use a statement such as "=true" or "=false". The following wording is not good:
if (if_love_delphi=true) and
(If_love_linux=false) Then
Donottrylinux;
For a function's return value or if a property is Boolean, this should be the case:
If If_love_delphi and
Not If_love_linux Then
Donottrylinux;
Advice four
Try not to use the "+" operator for string merging. It's too inefficient to do that. The following example is not good:
ShowMessage (' under Height ' +inttostr (iheight) + ' m, Weight ' +inttostr (iweight) + ' kg. ‘);
It would be better to write this:
ShowMessage (Format (' under Height%d, weight%d. ', [iheight,iweight]);
Advice five
Use the WITH statement as much as possible. It is not only efficient, but also makes the code easier to read. For example, this code:
If Sender if Tedit then
if (Tedit (Sender). Text= ') or
(Tedit (Sender). Text[tedit (Sender). Selstart]= ') or
(Tedit (Sender). Sellength=
Length (Tedit (Sender). Text))
and (Key in [' A ' ... ') Z ']) then
Key:=uppercase (Key);
This is not as easy to read as this code:
If Sender is Tedit then
With Sender as Tedit do
if (text= ') or
(text[selstart]= ') or
(Sellength=length (Text)) and
(Key in [' a ' ...] Z '] Then
Key:=upcase (Key);
(*//
Title: Recommended Statements in Delphi
Finishing: Zswang
Connection: http://www.csdn.net/Expert/TopicView1.asp?id=724036
Date: 2002-06-22
Support: wjhu111#21cn.com
//*)
{The most-determined logical type}
var B:boolean;
Begin
B: = Boolean (2); This is just for debugging//b: = True;
If B = True Then ShowMessage (' B = true '); Not recommended//unsafe
///////
If B then ShowMessage (' B '); Suggestion//Brief
End
var B:boolean;
Begin
If Edit1.text = ' yes ' then//not recommended//cumbersome
B: = True
else B: = False;
///////
B: = Edit1.text = ' yes '; Suggestion//Brief
End
{no.2 temporary SQL query}
Begin
Querytemp.close;
QueryTemp.SQL.Text: = ' SELECT SUM (amount) as Total from sales table ';
Querytemp.open; Not recommended//data is not closed resulting in waste of resources
ShowMessage (query1.fieldbyname (' total '). asstring);
/////
QueryTemp.SQL.Text: = ' SELECT SUM (amount) as Total from sales table ';
Querytemp.open;
ShowMessage (query1.fieldbyname (' total '). asstring);
Querytemp.close; recommended to use//close when used
End
{No.3 gets the number of records}
Var
Vrecordcount:integer;
Begin
Query1.SQL.Text: = ' SELECT * from Table1 '; Do not recommend//serious waste of resources, will get a lot of unnecessary information
Query1.open;
Vrecordcount: = Query1.recordcount;
Query1.close;
/////
Query1.SQL.Text: = ' SELECT count (*) as record count from Table1 '; Recommended//fast and effective, only one record is processed
Query1.open;
Vrecordcount: = Query1.fieldbyname (' Number of records '). Asinteger;
Query1.close;
ShowMessage (IntToStr (Vrecordcount));
End
{No.4 field Assignment}
Begin
Table1.edit;
Table1.fieldbyname (' name '). Asstring: = Edit1.text; Not recommended
Table1.fieldbyname (' Date '). Asdatetime: = Date;
/////
table1[' name ']: = Edit1.text; Advice//short, good extensibility
table1.fieldvalues[' name ']: = Edit1.text; Borland the recommended method. and paramvalues[]
table1[' Date ']: = date;
End
{No.5 using the self pointer}
Begin
Edit1.parent: = Form1; Not recommended//form1 is just a variable//What if there is no resource allocated?
///////
Edit1.parent: = self; Suggestions
End
{no.6 traversal data set}
Var
I:integer;
Begin
Query1.first;
For I: = 0 to Query1.recordcount-1 do begin//not recommended//easy to be affected
Query1.next;
{ };
End
/////
Query1.first;
While not query1.eof do begin//suggestion
{ };
Query1.next;
End
End
{No.7 uses the sender parameter to make the code generic}
Procedure Tform1.edit1change (Sender:tobject);
Begin
If Edit1.text = "then//not recommended
Edit1.color: = clred;
///////
If Tedit (Sender). Text = "then//suggestion//Copy to Editxchange very convenient
Tedit (Sender). Color: = clred;
End
{No.8 uses the default conversion function}
Var
I:integer;
Begin
I: = Strtoint (Edit1.text); Not recommended
///////
I: = Strtointdef (edit1.text, 0);//suggestion//reference strtofloatdef,strtodatedef .... But these are only Delphi6.
End
{no.9 traversal array}
Var
I:integer;
A:ARRAY[0..9] of Integer;
Begin
For I: = 0 to 9 do//not recommended
A[i]: = I;
///////
For I: = Low (a) to high (a) do//suggestion//extensibility Good
A[i]: = I;
End
{No.10 using Maxint constants}
Begin
Caption: = Copy (Edit1.text, 3, Length (Edit1.text)-3 + 1); Not recommended
///////
Caption: = Copy (Edit1.text, 3, MaxInt); Suggestion//Hee-ha, calculate less once
End
{No.11 result function pointer}
function Funcname:boolean;
Begin
FuncName: = True; Not recommended//and placed on the right of the assignment number cannot be a normal variable
///////
Result: = True; Suggestion//Extensibility is good
End
function funcsum (A:array of Integer): integer;
var I:integer;
Begin
Result: = 0;
For I: = Low (a) to high (a) do
Result: = result + A[i]; Can not be used funcsum: = Funcsum + a[i];
End
{No.12 must execute code, use Try ... finally ... end statement}
Var
Vstringlist:tstringlist;
Begin
Vstringlist: = tstringlist.create;
Vstringlist.loadfromfile (' c:\temp.txt ');
ShowMessage (Vstringlist.text);
Vstringlist.free; Not recommended//If an exception occurs resources will not be released
///////
Vstringlist: = tstringlist.create;
Try
Vstringlist.loadfromfile (' c:\temp.txt ');
ShowMessage (Vstringlist.text);
Finally//suggestion//Even if exit occurs, it will be executed
Vstringlist.free;
End
End
Other conditions 1
Begin
Screen.cursor: = Crhourglass;
Try
{Time-consuming operation}
Finally
Screen.cursor: = Crdefault;
End
End
Other conditions 2
Begin
Query1.disablecontrols;
Try
{Manipulate data Set}
Finally
Query1.enablecontrols;
End
End
The Boolean attribute (Boolean) of the >> object is automatically initialized to False (0);
>> integer variable (integer), automatically initialized to 0;
The >> string, which is automatically initialized to an empty string.
This is not necessarily
Local variables are best initialized, or they can cause inexplicable errors.
In particular: Integer, String, Pointer
I have experience
table1[' name ']: = Edit1.text; This is possible, but if:
Edit1.text: = table1[' name ']//This is absolutely not, because this time if NULL will be an error to Fieldbyname
Have found the answer, ansistring can also be used in format and sprintf "%s" in the reference.
I think a few two or three ansistring can still use "+" to connect, and more ansistring should use sprintf or format.
Compare
STRMSG = "Name:" + name + "Ages:" + inttostr (age) + "number:" + inttostr (num) + "Salary:" + inttostr (Salary);
And
strmsg.sprintf ("Name:%s Age:%d number:%d Salary:%d", name,age,num,salary);
The latter is more readable than the former, generating a machine code of only 1/3, more importantly, you can put the format string in the sprintf to focus on maintenance, and the former with "+" caused by a large number of fragmented string is not good processing.
The only disadvantage of the latter is that when there are a large number of parameters, it takes a little time to align the format string with the corresponding parameter.
Tip 1: If you want to use the with, think about refactoring and use it as a function
Tip 2: For close of datasets, use
Try
Dataset.open;
Finally
Dataset.close;
End
Tip 3: When using sender, please first determine if it is nil, is not the type you want
Advice 4:fieldvalue The handling of NULL is really poor, please use Fieldbyname (). Asxxxxx this
Tip 5: If you're going to write a long judgment, do it as a function, don't write it into an if then, and in a few days, you won't understand.
1, about with, I personally do not like to use, because he brought the readability is very poor. A parameter class, a few properties of the time, with the good, but also the project group of people to be more skilled in this class! If you have more than two parameter classes, God knows how to read this small segment of the with code.
2, about the string, with + and format these two I generally look at the situation. Some strings border with format is very bad to make, such as some of the spelling of SQL statements, multiple SQL with + Connection code readability is high. And the efficiency is good! However, some of the landlord mentioned the string, of course, with format is good, the same easy to read, I think in the use of the character (string) operation when the readability is the main, if with efficiency on the top, long string processing, I think is already a design problem.
3. For the comparison of for and while, the traversal of the dataset is of course used while. RecordCount unless you do not have a data set transition, if it is used, the system is large, and maintenance of your death, unpredictability is too high. It's not a matter of efficiency, it's a question of whether you write software that doesn't work.
4, about Fieldbyname. Well, I've been using it for a long time. Unless special temperament will use fields[]. Otherwise, when someone else's software is given to you for maintenance, you just wait to cry, check the fields and you'll have to spend all your overtime.
Maybe I don't make sense, everyone points out, if can prove better, so I learned something.
5 Tips to make code concise in Delphi (GO)