Delphi code snippets 1

by Radek Červinka 8. September 2010 22:53

I like to watch how others do code and let yourself be inspired. And here and there I encounter a piece of code that I am interested.

Very good source is VCL and I so many times find there a very interesting code. Like these, which is often used elsewhere.

This type of code is in VCL used many times, but this part is extra nice, especially code with Alignments I never thought (two-dimensional initialized array).

    1procedure TCustomEdit.CreateParams(var Params: TCreateParams);
    3  Alignments: array[Boolean, TAlignment] of DWORD =
    5  Passwords: array[Boolean] of DWORD = (0, ES_PASSWORD);
    6  ReadOnlys: array[Boolean] of DWORD = (0, ES_READONLY);
    7  CharCases: array[TEditCharCase] of DWORD = (0, ES_UPPERCASE, ES_LOWERCASE);
    8  HideSelections: array[Boolean] of DWORD = (ES_NOHIDESEL, 0);
    9  OEMConverts: array[Boolean] of DWORD = (0, ES_OEMCONVERT);
   10  NumbersOnlyStyle: array[Boolean] of DWORD = (0, ES_NUMBER);
   12  inherited CreateParams(Params);
   13  CreateSubClass(Params, 'EDIT');
   14  with Params do
   15  begin
   16    Style := Style or (ES_AUTOHSCROLL or ES_AUTOVSCROLL) or
   17      Alignments[UseRightToLeftAlignment, FAlignment] or
   18      BorderStyles[FBorderStyle] or Passwords[FPasswordChar <> #0] or
   19      NumbersOnlyStyle[FNumbersOnly] or
   20      ReadOnlys[FReadOnly] or CharCases[FCharCase] or
   21      HideSelections[FHideSelection] or OEMConverts[FOEMConvert];
   22    if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then
   23    begin
   24      Style := Style and not WS_BORDER;
   25      ExStyle := ExStyle or WS_EX_CLIENTEDGE;
   26    end;
   27  end;

Just to be sure: we have a few constants of type array of initialized values, where the dimension of the field determined by a type (often Boolean, which is actually the interval 0..1). Then simply access value in array and use the resulting value in an expression. It's short, I believe clear and very efficient from a performance, because the program has no jumps, so the processor does not solve predication of branches and so.

Tags: ,


Comments are closed