Functional programming style in Delphi

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);
  Ctx: TRttiContext;
  P: TRttiProperty;
  T: TRttiType;

  T:= Ctx.GetType(TButton);
  P:= T.GetProperty('Caption');
  P.SetValue(Button1, 'RTTI');

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);
  TRttiContext.Create.GetType(TButton).GetProperty('Caption').SetValue(Button1, 'RTTI');

All variables have gone. No memory leaks. Does your brain hurt?


11 thoughts on “Functional programming style in Delphi

  1. in imperative programming : programs are composed of statements which change global state when executed.

    It is happening in your code.

    • IMO, the change of a state always take place on some level, because that is how the computers work. The functional programming is just on some higher level. Though Delphi is definitely an imperative language, the second code snippet is an example of functional approach to programming.

  2. This defeats the whole purpose of RAD programming. There’s a button firing the event, the method is conveniently named after the component that fired it, the component is kind enough to push its “self” on the stack and all this precious info is subsequently ignored…

  3. In my case when I execute TRttiContext.Create, I get an exception that says an access violation has occured at addreess: read of address 0x00000000. I am working with Delphi Xe2 with a program that was orginally written in Delphi 2007. The call to TRttiContext is something I am trying to put in.

  4. I need help with functions and calculating vars and also assigning values or text to var as a constant variable. Pleeeeaaasssee help

  5. Pingback: Программирование в функциональном стиле в Delphi | 2.0

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s