So I just found the following lovely piece of code in one of our forms:

So I just found the following lovely piece of code in one of our forms:

var
  code: string;
  codeNotFound: boolean; 
begin
  ...
  code := ...;
  codeNotFound := not DataSet.Locate(...);
  if codeNotFound then
  begin
    PostMessage(Handle,WM_WARN01,Integer(PChar(code)),0);
  end;
  ...
end;

procedure Tfrm.WMWarn01(var msg: TMessage);
begin
  ShowMessage('Code "' + PChar(msg.wParam) + '" not found');
  cmbCode.SetFocus;
end;

Such horror... yet doing such async things correctly was such a chore before.

Fortunately times have changed and thanks to anonymous procedures it's now trivial to get the code right. In my opinion it also helps readability by keeping things local:

  ...
 if codeNotFound then
  begin
    async.Post(
      procedure
      begin
        ShowMessage('Code "' + code + '" not found');
        cmbCode.SetFocus;      
      end
    );
  end;
  ...

Here "async" is just a a trivial non-visual component which allocates a window handle. The Post method does a PostMessage call and the message handler executes the supplied anonymous procedure. The full code is here: http://pastebin.com/5t7TRfpb


The difference is of course that anonymous procedures captures variables, and so this is safe unlike the original code.

While anonymous procedures is not a new feature, it seems just about none of my coworkers knew about them and what they're good for... I hope this can convince them to learn up on some of the "newfangled" features ;)
http://pastebin.com/5t7TRfpb

Comments