Quantcast
Channel: Delphi – The Wiert Corner – irregular stream of stuff
Viewing all articles
Browse latest Browse all 1440

It pays to closely look to your coding

$
0
0

I like questions like [WayBack] How to check if parent menu item has “checked” child item? – VCL – Delphi-PRAXiS [en]

It means that the asker is closely looking at her or his coding.

This is important, as it helps to get your programming idioms consistent.

The code started out as:

function HasCheckedSubItems(AMenuItem: TMenuItem): Boolean;
var
  i: integer;
begin
  Result := False;
  for i := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[i].Checked then
      Exit(True);
end;

and finally ended up as:

function HasCheckedSubItems(AMenuItem: TMenuItem): Boolean;
var
  I: integer;
begin
  for I := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[I].Checked then
      Exit(True);
  Exit(False); 
end;

Which is close to what I’d use, no matter the Delphi version:

function HasCheckedSubItems(const AMenuItem: TMenuItem): Boolean;
var
  I: integer;
begin
  for I := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[I].Checked then
    begin
      Result := True;
      Exit;
    end;
  Result := False;
end;

My argumentation for the last form is that assignment and jumps are too conceptually different to combine in one statement.

The second form moves just one assignment, which on the current scale of nanosecond execution might not sound much, but conceptually limits the assignment to once per function call.

If you are interested in more thoughts on this topic,

  1. read How to Design Early Returns in C++ (Based on Procedural Programming) – Fluent C++
  2. watch Procedural Programming: It’s Back? It Never Went Away – Kevlin Henney [ACCU 2018] – YouTube
  3. save the slides from [WayBack

–jeroen


Viewing all articles
Browse latest Browse all 1440

Trending Articles