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.
if SomeBoolean then
begin
...
end else
if Something then
begin
end else
ErrorMessage := 'This is an error';
Inc(ErrorCount);
Hard to spot.
begin...end blocks cost nothing in run time but can be priceless in debugging time. I need to be more diligent myself. :)
ReplyDeleteIndeed. I have some strict exceptions (exit call fex), otherwise I'm wrapping it all in begin..end.
ReplyDeleteCorrect Code formatting is your friend ;)
ReplyDeleteAlso, put the "else" on a new line. At least this is what i prefer.
ReplyDeleteYes, 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.
ReplyDeletePhillip 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...
ReplyDeleteI never put begin..end around 1-line block ('Borland Style' he-he).
ReplyDeleteI sometimes see the code blocks ending with
end;
end;
end;
end;
end;
...
and it makes me a litte bit crazy :)
Igor Schevchenko Really? I love seeing that beautiful cascade of end statements. ;-)
ReplyDeleteNick Hodges 10 ends is not the limit :)
ReplyDeleteI 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:
ReplyDeleteif SomeBoolean then
begin
...
end
else if Something then
begin
...
end
else
ErrorMessage := 'This is an error';
Inc(ErrorCount);
That's why I and all my colleagues use the GExperts code formatter.
ReplyDeleteDaniela Osterhagen I ALWAYS use code formatting tools, DelForExp (or JCF) for D2006 and built-in in later Delphi versions
ReplyDeleteI simply type begin and
ReplyDelete. ........ Castalia inserts the 'end' and formats the indented code
Steven Healey The Code Completion of the IDE is doing that -- I don't think it is Castalia. ;-)
ReplyDeleteI love CnPack's color coded begin..end connectors. Makes it blatantly obvious what level of nesting a line of code is in.
ReplyDeleteMy 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.