Functional programming paradigm gradually finds its way even in Delphi – an imperative language without a garbage collector. Consider the next code sample that changes a button’s caption using extended RTTI (requires Delphi 2010 and above):
procedure TForm1.Button1Click(Sender: TObject); var Ctx: TRttiContext; P: TRttiProperty; T: TRttiType; begin T:= Ctx.GetType(TButton); P:= T.GetProperty('Caption'); P.SetValue(Button1, 'RTTI'); end;
When analyzing the above code snippet note the following:
- TRttiContext is a record type; you need not create and destroy a variable of a record type
- TRttiProperty and TRttiType types are classes; the instances of these classes are created by correspondent TRttiType and TRttiContext methods, but you should not destroy these instances yourself – the underlying extended RTTI implementation takes care about it
As a result the above code snippet can be rewritten in a functional style:
procedure TForm1.Button1Click(Sender: TObject); begin TRttiContext.Create.GetType(TButton).GetProperty('Caption').SetValue(Button1, 'RTTI'); end;
All variables have gone. No memory leaks. Does your brain hurt?