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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With