Here's why I always always always put a begin...end around every statement. I just had to fix a bad, hard to see bug like the following.....

Here's why I always always always put a begin...end around every statement.  I just had to fix a bad, hard to see bug like the following.....

if SomeBoolean then
begin
...
end else
  if Something then
  begin
  end else
    ErrorMessage := 'This is an error';
    Inc(ErrorCount);


Hard to spot.

Comments

  1. begin...end blocks cost nothing in run time but can be priceless in debugging time. I need to be more diligent myself. :)

    ReplyDelete
  2. Indeed. I have some strict exceptions (exit call fex), otherwise I'm wrapping it all in begin..end.

    ReplyDelete
  3. Correct Code formatting is your friend ;)

    ReplyDelete
  4. Also, put the "else" on a new line. At least this is what i prefer.

    ReplyDelete
  5. Yes, I've gotten into the habit of putting begin end around every block, even if that block is only 1 line.   Not only is it clearer, but it will prevent a lot of bugs.

    ReplyDelete
  6. Phillip Woon It also saves you a lot of hassle when you figure out you needed two lines in that if block instead of just one...

    ReplyDelete
  7. I never put begin..end around 1-line block ('Borland Style' he-he).
    I sometimes see the code blocks ending with
             end;
           end;
         end;
       end;
     end;
    ...
    and it makes me a litte bit crazy :)

    ReplyDelete
  8. Igor Schevchenko  Really?  I love seeing that beautiful cascade of end statements.  ;-)

    ReplyDelete
  9. Nick Hodges 10 ends is not the limit :)

    ReplyDelete
  10. I never surround oneline code with begin end. For me that is just noise in the code. But formatting is important! I would change the example to:

    if SomeBoolean then
    begin
    ...
    end
    else if Something then
    begin
    ...
    end
    else
    ErrorMessage := 'This is an error';

    Inc(ErrorCount);

    ReplyDelete
  11. That's why I and all my colleagues use the GExperts code formatter.

    ReplyDelete
  12. Daniela Osterhagen I ALWAYS use code formatting tools, DelForExp (or JCF) for D2006 and built-in in later Delphi versions

    ReplyDelete
  13. I simply type begin and
    . ........ Castalia  inserts the 'end' and formats the indented code

    ReplyDelete
  14. Steven Healey The Code Completion of the IDE is doing that -- I don't think it is Castalia.  ;-)

    ReplyDelete
  15. I love CnPack's color coded begin..end connectors. Makes it blatantly obvious what level of nesting a line of code is in.

    My personal preference is to "Extract Method" anytime a branch has more than 2 or three lines of code. When structured this way there's very little nesting at all and the resulting methods are very short and trivial to understand.

    ReplyDelete

Post a Comment