本文為 Delphi 程式碼規範系列第一部分的第 3 節,涵蓋列舉類型、陣列類型、記錄類型、類別定義、類別變數、方法命名與屬性存取方法 (Getter/Setter) 規範。
3.4.3 列舉類型
- 類型名稱:有意義、T 前綴 (如
TSongType)
- 列舉值:包含類型簡稱 (如
stRock, stClassical, stCountry)
type
TSongType = (stRock, stClassical, stCountry, stAlternative, stHeavyMetal, stRB);
3.4.4 陣列類型
- 類型名稱:有意義、T 前綴
- 指標類型:P 前綴 + 陣列類型名 (如
PCycleArray = ^TCycleArray)
type
PCycleArray = ^TCycleArray;
TCycleArray = array[1..100] of Integer;
3.4.5 記錄類型
- 類型名稱:有意義、T 前綴
- 指標類型:P 前綴 + 記錄類型名 (如
PEmployee = ^TEmployee)
type
PEmployee = ^TEmployee;
TEmployee = record
EmployeeName: string;
EmployeeRate: Double;
end;
3.5 類別設計規範
3.5.1 類別命名與格式
- 類別名:有意義、T 前綴 (如
TCustomer = class(TObject))
- 實例變數:去掉 T 前綴 (如
Customer: TCustomer)
3.5.2 類別變數 (Fields)
- 命名:有意義、F 前綴 (如
FUserName: string)
- 封裝性:所有變數必須為 private/protected
- 外部存取:必須透過屬性 暴露
3.5.3 方法命名
- 遵循一般函數/程序命名規則 (PascalCase,有意義單詞)
3.5.3.2 屬性存取方法 (關鍵規範)
| 規則 | 說明 | 範例 |
| 可見度 | 必須置於 private 或 protected | private ... function GetAge: Integer; |
| 讀取方法前綴 | Get | function GetUserName: string; |
| 寫入方法前綴 | Set | procedure SetUserName(Value: string); |
| 寫入參數名 | 統一命名為 Value,型別與屬性一致 | procedure SetAge(Value: Integer); |
type
TSomeClass = class(TObject)
private
FSomeField: Integer;
protected
function GetSomeField: Integer;
procedure SetSomeField(Value: Integer);
public
property SomeField: Integer read GetSomeField write SetSomeField;
end;
完整類別範例
type
TCustomer = class(TObject)
private
FId: Integer;
FName: string;
FEmail: string;
function GetId: Integer;
procedure SetId(Value: Integer);
function GetName: string;
procedure SetName(Value: string);
function GetEmail: string;
procedure SetEmail(Value: string);
protected
// 受保護的存取方法供子類別覆寫
function GetDisplayName: string; virtual;
public
constructor Create(AId: Integer; const AName, AEmail: string);
property Id: Integer read GetId write SetId;
property Name: string read GetName write SetName;
property Email: string read GetEmail write SetEmail;
property DisplayName: string read GetDisplayName; // 唯讀屬性
end;
implementation
function TCustomer.GetId: Integer;
begin Result := FId; end;
procedure TCustomer.SetId(Value: Integer);
begin
if Value > 0 then FId := Value; // 可加入驗證邏輯
end;
function TCustomer.GetDisplayName: string;
begin
Result := Format('%s (%s)', [FName, FEmail]);
end;
核心原則總結
- 封裝優先:欄位私有,屬性公開
- 命名一致:Get/Set + 屬性名,參數固定為 Value
- 可擴充:存取方法置於 protected 允許繼承覆寫
- 驗證集中:Setter 內攔截非法值,保護物件不變式
遵循此規範撰寫的類別,具備高內聚、低耦合、易測試、易維護的特性,是 Delphi 物件導向開發的基石。
- 上一篇文章: Delphi 原始碼格式撰寫規範(二):專案目錄結構、檔案命名與組件簡稱對照表
- 下一篇文章: Delphi 原始碼格式撰寫規範(一)第 2 節:變數命名、區域/全域變數與類型大小寫協定
Copyright ©
程式碼之家 All Rights Reserved