寫程式是一種藝術。Delphi 讓任何人都能輕鬆開發軟體,但優雅、高效、可維護的程式碼唯有高手能寫出。除了正確縮排、大小寫、命名規範,請時刻銘記:簡單就是美。以下五個常見問題,初學者甚至資深開發者都容易踩雷。
❌ 不好:
if If_Love_Delphi then
Result := True
else
Result := False;
✅ 好:
Result := If_Love_Delphi;
延伸:初始化布林變數時,False 是預設值 (Delphi 自動將布林、整數、字串、物件布林屬性初始化為 0/False/空字串),var B: Boolean; 直接可用,無需額外指派 B := False。
❌ 囉嗦:
if If_Love_Delphi then
if If_Love_Linux then
TryKylix(Now);
✅ 簡潔:
if If_Love_Delphi and If_Love_Linux then
TryKylix(Now);
補充:Delphi 預設關閉「Complete Boolean eval」(專案選項 → Compiler → Syntax Options),採用短路求值,第二個條件不會在第一個為 False 時執行,安全且高效。
綜合範例:
{ 原本 }
if If_Love_Delphi then
if If_Love_Linux then
Result := True;
{ 改寫 }
Result := If_Love_Delphi and If_Love_Linux;
❌ 多餘:
if (If_Love_Delphi = True) and (If_Love_Linux = False) then
DoNotTryLinux;
✅ 自然:
if If_Love_Delphi and not If_Love_Linux then
DoNotTryLinux;
同理,函式回傳布林或布林屬性,直接用於 if 條件即可。
❌ 低效:
ShowMessage('身高' + IntToStr(iHeight) + '米,體重' + IntToStr(iWeight) + '公斤。');
✅ 高效且易讀:
ShowMessage(Format('身高%d米,體重%d公斤。', [iHeight, iWeight]));
Format 避免多次記憶體重新配置,格式字串集中維護,支援對齊、精度等豐富格式化選項。
❌ 冗長難讀:
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); // 單字元用 UpCase 更合適
with 減少重複類型轉換與屬性存取,編譯器最佳化下效率不降反增。
這五條法則的核心精神是:消除冗餘、表達意圖、信任編譯器。養成習慣後,程式碼行數減少、Bug 率下降、維護成本大幅降低。從今天開始,寫每一行碼前問自己:「還能更簡潔嗎?」