2006. június 22., csütörtök

The power of accessors


Problem/Question/Abstract:

Making properties in your objects and using the accesors to do something.

Answer:

Property accessors are great.  They give you the power to do stuff like initialize an object or produce data that are dependent on the object's other properties.

You can make properties by declaring them in your interface section and then pressing Ctrl+Shift+'c'  it wil make a private variable called Fsomeproperty and a set methode called SetSomeProperty.

In this example i made an object that has a property that holds an other object and on the Read of this property i'll check whether it's not nil so i can create it on runtime.

You can also check if a value is within it's bounds on the Property's Set Accessor

type
  TMySubObject = class

  end;

  TMyObject = class
  private
    fMySubObject: TMySubObject;
    FASecondNum: Integer;
    FAFirstnum: Integer;
    function getMySubObject: TMySubObject;
    function GetTotaalOfFirstAndSecondNum: integer;
    procedure SetFirstnum(const Value: Integer);
  public

    property MySubObject: TMySubObject read getMySubObject;
    property AFirstnum: Integer read FAFirstnum write SetFirstnum;
    property ASecondNum: Integer read FASecondNum write FAFirstnum;
    property TotaalOfFirstAndSecondNum: integer read
      GetTotaalOfFirstAndSecondNum;
  end;

implementation

{$R *.DFM}

{ TMyObject }

function TMyObject.getMySubObject: TMySubObject;
begin
  // i check here to see if its assigned
  if not Assigned(fMySubObject) then
    fMySubObject := TMySubObject.Create;
  Result := fMySubObject;
end;

function TMyObject.GetTotaalOfFirstAndSecondNum: integer;
begin
  Result := FAFirstnum + FASecondNum;
end;

procedure TMyObject.SetFirstnum(const Value: Integer);
begin
  // here on the set u can check bounds :) .
  if (Value > 0) and (Value < 1000) then
    FAFirstnum := Value
  else
    raise Exception.Create('Number out of bounds');
end;

Nincsenek megjegyzések:

Megjegyzés küldése