这是一个编码风格问题,可能不会在这里存在很长时间。:-) (编码风格在很大程度上是个人意见的问题,那里有很多不同的。)无论如何,我会试一试。:-)
我会做的稍微不同。if..else
IMO,这清楚地显示begin..end
了新程序员的正确配对:
begin
if Password <> Database['Database'] then
showmessage ('Message')
else
if NewPassword <> Retype then
showmessage ('Message')
else
begin
if Message (yes, No, etc) = yes then
begin
List;
List;
List.post;
showmessage ('Message');
end
else
close;
end;
end;
在我自己的代码中,我仍然会做一些不同的事情(但只有很小的区别)。我会将 移动else
if password
到同一行(它减少了一级缩进,对我来说使代码流更加清晰。我们有三个可能的选项,并且清楚地显示了三个选项(if this
, else if this
, else this
):
begin
if Password <> Database['Database'] then // option 1
showmessage ('Message')
else if NewPassword <> Retype then // option 2
showmessage ('Message')
else // option 3
begin
if Message (yes, No, etc) = yes then
begin
List;
List;
List.post;
showmessage ('Message');
end
else
close;
end;
end;
只有几个其他代码区域的格式有时会有所不同。我会尝试尽可能多地快速触摸它们。
案例陈述:
case i of
0: DoThingForZero; // Only one line to execute for 0
1: begin // Two things to do for 1
DoSetupForOne;
DoThingForOne;
end;
2: DoThingForTwo;
else // Handle anything other than 0, 1, 2
DoThingsForOtherValues;
end;
虽然语句:
while not Query1.Eof do
begin
// Process each field in current record of table
Query1.Next; // Move to next row (easy to forget, infinite loop happens. :-)
end;
重复语句:
i := 1;
repeat
i := i + SomeFunctionResultReturningVariousValues();
until (i > 50)
对于循环:
for i := 0 to List.Count - 1 do
begin
ProcessItem(List[i]);
end;
for i := List.Count - 1 downto 0 do
List[i].Delete;
For..in 循环:
for ch in SomeString do // For each character in a string,
WriteLn(ch, ' = ', Ord(ch)); // write the ordinal (numeric) value
ReadLn;
尝试..最后:
SL := TStringList.Create; // Create object/open file/whatever (resource)
try
// Code using resource
finally
SL.Free; // Free the resource
end;
尝试..除了:
try
// Do something that might raise an exception
except
on E: ESomeVerySpecificException do
begin
// Handle very specific exception
end;
on E: ESomeLessSpecificException do
begin
// Handle less specific exception
end;
else
raise;
end;
Try..finally 与 try..except:
SL := TStringList.Create; // Allocate resource
try
try
// Do something that might raise exception
except
// Handle exception as above
end;
finally
SL.Free; // Free resource
end;