寫代碼是一種藝術。使用Delphi,任何人都可以輕而易舉地開發出某種軟體、完成某些任務。而完美的代碼則只有真正的高手才能寫出。除了正確的縮排、大小寫、命名規則之外,請時刻牢記愛因斯坦的名言--簡單就是美。下面將談及的五個代碼問題,可能是初學者、甚至一些老鳥都會犯的錯誤。
忠告一
布爾型變數的賦值操作應該是直接的。例如,在一個if/then/else語句中,if子句將布爾型變數賦值為True,而else子句將其賦為False。下面這段代碼的寫法是不好的:
- if If_Love_Delphi then
- Result:=True
- else
- Result:=False;
-
- 而這樣寫就比較好:
-
- Result:= If_Love_Delphi;
if If_Love_Delphi then Result:=Trueelse Result:=False;而這樣寫就比較好:Result:= If_Love_Delphi;
忠告二
避免使用嵌套的if/then/if語句,而用and來代替。下面這段代碼太羅嗦:
- if If_Love_Delphi then
- if If_Love_Linux then
- TryKylix(Now);
-
- 應該這樣寫:
-
- if If_Love_Delphi and If_Love_Linux then
- TryKylix(Now);
if If_Love_Delphi then if If_Love_Linux thenTryKylix(Now);應該這樣寫:if If_Love_Delphi and If_Love_Linux then TryKylix(Now);
不用擔心後面的判斷語句會超前執行。Project|Options|Compiler|Syntax Options|Complete Boolean eval選項通常是關閉的(除非你選定這個項),這保證了執行順序不會顛倒。
綜合前兩個忠告,假如你有一段這樣的代碼:
- if If_Love_Delphi then
- if If_Love_Linux then
- Result:=True;
-
- 就可以把它改成:
-
- Result:= If_Love_Delphi and If_Love_Linux;
if If_Love_Delphi then if If_Love_Linux thenResult:=True;就可以把它改成:Result:= If_Love_Delphi and If_Love_Linux;
簡單而言,假如結果取決於一個條件判斷,那麼,Result:=True或者Result:=False這樣的語句就是多此一舉。在初始化布爾型變數的時候,可以給它們賦值。不過根本用不著把一個布爾型變數初始化為False--Delphi在建立這個變數的時候就已經把它賦職位False了。相似的情況還有:
對象的布爾型屬性(Boolean),自動被初始化為False (0);
整型變數(Integer),自動被初始化為 0;
字串(String),自動被初始化為空白字串。
忠告三
判斷布爾型變數的值時,無需用"=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;
if (If_Love_Delphi=True) and (If_Love_Linux=False) then DoNotTryLinux;對於函數的傳回值或者一個屬性是布爾型的情況,應該這樣寫:if If_Love_Delphi and not If_Love_Linux thenDoNotTryLinux;
忠告四
盡量不要用"+"操作符進行字串合并。這樣做效率太低了。下面的例子不好:
- ShowMessage('在下身高'+IntToStr(iHeight)+'米,體重'+IntToStr(iWeight)+'公斤。');
-
- 這樣寫會較好:
-
- ShowMessage(Format('在下身高%d,體重%d。', [iHeight,iWeight]));
ShowMessage('在下身高'+IntToStr(iHeight)+'米,體重'+IntToStr(iWeight)+'公斤。');這樣寫會較好:ShowMessage(Format('在下身高%d,體重%d。', [iHeight,iWeight]));
忠告五
盡量多用with語句。它不僅效率高,而且使代碼更加易讀。比如,這段代碼:
- if Sender is 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);
-
- 就不如這樣的代碼來得簡潔易讀:
-
- 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);
http://vir.jxstnu.edu.cn/xieyunc/read.php?29