The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 4,262 other subscribers

It pays to closely look to your coding

Posted by jpluimers on 2020/12/31

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

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.