Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeated setters logic in Delphi

For each setter of a class I have to implement some event logic (OnChanging, OnChanged):

procedure TBlock.SetWeightIn(const Value: Double);
var OldValue: Double;
begin
  OldValue := FWeightIn;
  DoOnChanging(OldValue, Value);
  FWeightIn := Value;
  DoOnChanged(OldValue, Value);
end;

procedure TBlock.SetWeightOut(const Value: Double);
var OldValue: Double;
begin
  OldValue := FWeightOut;
  DoOnChanging(OldValue, Value);
  FWeightOut := Value;
  DoOnChanged(OldValue, Value);
end;

Can you please suggest a way to implement this without duplicating all these lines for each setter?

like image 205
Tihauan Avatar asked Jul 23 '09 07:07

Tihauan


2 Answers

Try this:

procedure TBlock.SetField(var Field: Double; const Value: Double);
var
    OldValue: Double;
begin
    OldValue := Field;
    DoOnChanging(OldValue, Value);
    Field := Value;
    DoOnChanged(OldValue, Value);
end;

procedure TBlock.SetWeightIn(const Value: Double);
begin
    SetField(FWeightIn, Value);
end;

procedure TBlock.SetWeightOut(const Value: Double);
begin
    SetField(FWeightOut, Value);
end;
like image 144
Cobus Kruger Avatar answered Oct 20 '22 04:10

Cobus Kruger


Delphi supports indexed properties. Multiple properties can share a single getter or setter, differentiated by an ordinal index:

type
  TWeightType = (wtIn, wtOut);
  TBlock = class
  private
    procedure SetWeight(Index: TWeightType; const Value: Double);
    function GetWeight(Index: TWeightType): Double;
  public
    property InWeight: Double index wtIn read GetWeight write SetWeight;
    property OutWeight: Double index wtOut read GetWeight write SetWeight;
  end;

You can combine this with Cobus's answer to get this:

procedure TBlock.SetWeight(Index: TWeightType; const Value: Double);
begin
  case Index of
    wtIn: SetField(FWeightIn, Value);
    wtOut: SetField(FWeightOut, Value);
  end;
end;

This might give you ideas for other ways you can refer to your fields by index instead of having two completely separate fields for such related values.

like image 34
Rob Kennedy Avatar answered Oct 20 '22 05:10

Rob Kennedy