Coding Style

31.7.04

Recently Nick has posted some weird codes found in the projects he now maintains. It's good idea for us to share different coding style, no matter it is excellent or stupid.
Today I find a piece of codes as the follow:
  if radOption.ItemIndex = 0 then
  begin
    if edtName.Text <> '' then
    begin
      DOTask1;
    end;
  end
  else
  begin
    DoTask2;
  end;

The begin..end blocks are very common in our code but sometimes they are redundant. Anyone want to try?


Comments:
I dont really have a problem with redundant begin/end blocks, but would format it as.

if radOption.ItemIndex = 0 then
begin
if edtName.Text <> '' then
begin
DOTask1;
end;
end else
begin
DoTask2;
end;

Ahh, what happened to my spaces!

The space will be ignored here. You can type &nbsp; instead of the space bar.
By the way, what's the difference between the codes?

the "end else" are on the same line. I think

begin
...
end else
begin
...
end;

is better than

begin
...
end
else
begin
...
end

Style 1:
if ConditionA then
begin
  ...
end
else if ConditionB then
begin
  ...
end;
Style 2:
if ConditionA then
begin
  ...
end
else
if ConditionB then
begin
  ...
end;
I don't like Style 1 where "else if" are on the same line. It seems less easier to figure out all conditions when quick scanning it. But I know this pattern is very common.

Sorry JohnE, that will execute Task2 when ItemIndex<>0

if radOption.ItemIndex = 0 then
  if edtName.Text <> '' then
    DOTask1
  else
    DoTask2;

Hi Gloria, Personally i dont like to have strict rules on when i place then+else, especialy if it effects readability (my idea of readability that is!)

I'd lay it out like this:

if radOption.ItemIndex = 0 then
   if edtName.Text <> ''
     then DOTask1
     else DoTask2;

if the spaces don't come through, you'll have to imagine the indentation yourself :)

Eamonn

Hm, my favorite is:

if radOption.ItemIndex = 0 then begin
  if edtName.Text <> '' then begin
    DOTask1;
  end;
end
else begin
  DoTask2;
end;

but apparently not much used :)

I use the begin/end whenever the binding is ambiguous - so I'm sure what the 'else' relates to...

if Test1 then
begin
   if Test2 then
      DOTask1;
end
else
   DoTask2;

-- the worse situation is when the indenation doesn't match the binding, like

if Test1 then
   if Test2 then
     DoTask1;
else
  DoTask2;

We have our own preference :)

Post a Comment

<< Home