首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 原始碼格式撰寫規範(一)第 3 節:列舉/陣列/記錄類型、類別設計與屬性存取方法

     編輯:Delphi

本文為 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 屬性存取方法 (關鍵規範)


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;

核心原則總結

  1. 封裝優先:欄位私有,屬性公開
  2. 命名一致:Get/Set + 屬性名,參數固定為 Value
  3. 可擴充:存取方法置於 protected 允許繼承覆寫
  4. 驗證集中:Setter 內攔截非法值,保護物件不變式

遵循此規範撰寫的類別,具備高內聚、低耦合、易測試、易維護的特性,是 Delphi 物件導向開發的基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
規則說明範例
可見度必須置於 private 或 protectedprivate ... function GetAge: Integer;
讀取方法前綴Getfunction GetUserName: string;
寫入方法前綴Setprocedure SetUserName(Value: string);
寫入參數名統一命名為 Value,型別與屬性一致procedure SetAge(Value: Integer);