Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use block identifiers ("end;") in my code?

Code Complete says it is good practice to always use block identifiers, both for clarity and as a defensive measure.

Since reading that book, I've been doing that religiously. Sometimes it seems excessive though, as in the case below.

Is Steve McConnell right to insist on always using block identifiers? Which of these would you use?

//naughty and brief
with myGrid do
  for currRow := FixedRows to RowCount - 1 do
    if RowChanged(currRow) then
      if not(RecordExists(currRow)) then
        InsertNewRecord(currRow)
      else
        UpdateExistingRecord(currRow);

//well behaved and verbose
with myGrid do begin
  for currRow := FixedRows to RowCount - 1 do begin
    if RowChanged(currRow) then begin
      if not(RecordExists(currRow)) then begin
        InsertNewRecord(currRow);
      end  //if it didn't exist, so insert it
      else begin
        UpdateExistingRecord(currRow);
      end;  //else it existed, so update it
    end;  //if any change
  end;  //for each row in the grid
end;  //with myGrid 
like image 337
JosephStyons Avatar asked Jul 21 '09 18:07

JosephStyons


2 Answers

I have always been following the 'well-behaved and verbose' style, except those unnecessary extra comments at the end blocks.

Somehow it makes more sense to be able to look at code and make sense out of it faster, than having to spend at least couple seconds before deciphering which block ends where.

Tip: Visual studio KB shortcut for C# jump begin and end: Ctrl + ]

If you use Visual Studio, then having curly braces for C# at the beginning and end of block helps also by the fact that you have a KB shortcut to jump to begin and end

like image 71
Vin Avatar answered Oct 21 '22 04:10

Vin


Personally, I prefer the first one, as IMHO the "end;" don't tell me much, and once everything is close, I can tell by the identation what happens when.

I believe blocks are more useful when having large statements. You could make a mixed approach, where you insert a few "begin ... end;"s and comment what they are ending (for instance use it for the with and the first if).

IMHO you could also break this into more methods, for example, the part

  if not(RecordExists(currRow)) then begin
    InsertNewRecord(currRow);
  end  //if it didn't exist, so insert it
  else begin
    UpdateExistingRecord(currRow);
  end;  //else it existed, so update it

could be in a separate method.

like image 35
Samuel Carrijo Avatar answered Oct 21 '22 03:10

Samuel Carrijo