Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

星期二, 9月 11, 2007

Delphi 使程式碼簡潔的忠告

一、Boolean值操作應該是直接的
if If_Love_Delphi then
  Result:=True
else
  Result:=False;
改成這樣寫比較好:
Result:= If_Love_Delphi;

二、避免使用 if/then/if ,而用and来代替
例1:
if If_Love_Delphi then
  if If_Love_Linux then
    TryKylix(Now);
改成這樣寫比較好:
if If_Love_Delphi and If_Love_Linux then
  TryKylix(Now);
例2:
if If_Love_Delphi then
  if If_Love_Linux then
    Result:=True;
改成這樣寫比較好:
Result:= If_Love_Delphi and If_Love_Linux;

三、判斷boolean值時不需用"=True","=False"
if (If_Love_Delphi=True) and (If_Love_Linux=False) then
  DoNotTryLinux;
改成這樣寫比較好:
if If_Love_Delphi and not If_Love_Linux then
  DoNotTryLinux;


四、盡量不要用"+"來進行字串合併
ShowMessage('在下身高'+IntToStr(iHeight)+'尺,體重'+IntToStr(iWeight)+'公斤。');
改成這樣寫比較好:
ShowMessage(Format('在下身高%d,體重%d。', [iHeight,iWeight]));

五、盡量少用With,它不僅效率高,而且使程式碼更加容易讀
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);
改成這樣寫比較好:
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);

1 則留言:

小翰部落格 提到...

請問第五點,是建議使用還是不使用呢?因為前後意思好像互相牴觸....

因為有用看起來程式碼比較乾淨,但是如果效率高為什麼建議少用,這個地方我看不懂,請指教謝謝。

今天專心看你的部落格,寫的很棒。

五、盡量少用With,它不僅效率高,而且使程式碼更加容易讀