views:

796

answers:

19

As a long time Pascal and Delphi developer, I always line up my begin and ends thus :

begin
  if x = y then
  begin
     ...
     ...
  end
  else
    for i := 0 to 20 do
    begin
      ...
      ...
    end;
end;

What drives me nuts is code formatted thus :

begin
  if x = y then begin
     ...
     ...
  end
  else
    for i := 0 to 20 do begin
      ...
      ...
    end;
end;

When there are a few levels of compound statements I find this hard to read. The above code is ok, because it's not that complicated, but for consistency I'd prefer all begins and ends aligned.

As I start using c#, I find myself aligning curly brackets too. What's the norm in the C# world?

Edit :

Someone has pointed out that this is the type of question that shouldn't be asked on SO. I don't see why not. I'm in the process of setting up a coding guidelines document. I know I'll get some resistance to certain things, I'm hoping to get a few answers here, so I can be ready to meet that resistance head-on.

+1  A: 

Everybody has different preferences. In my case, I learned Modula-2 before I learned Pascal. Modula-2 has no BEGIN keyword, and a required END for every block. So code might look like this (Modula-2 happens to be case sensitive with uppercase keywords):

IF x = y THEN
    ....
END;

When I started to code in Pascal, this became:

if x = y then begin
    ....
end;

In this way, the code looked more like what I was used to seeing, while still being within the realm of acceptable Pascal code.

For me, these early impressions have influenced my preferred brace and indent style for virtually all other languages I've worked with. There is not really any particular "norm" for C# code, just as there is none for C or Pascal.

The only real rule to follow is this: When working on existing code, use the style that already exists. When working on new code, use your preferred style.

Greg Hewgill
A: 

This was asked before. for example c-coding-standard-best-practices.

gimel
A: 

I would never write the code (your second example) that way. It would be either (preferred)

begin
  if x = y then begin
     ...
  end
  else begin
    for i := 0 to 20 do begin
      ...
   end;
  end;
end;

or

begin
  if x = y then begin
     ...
  end
  else for i := 0 to 20 do begin
     ...
  end;

end;

Sometimes I use such collapsing (as in the second case) to combine if and try..finally.

x := GetMeTheObject;
if assigned(x) then try
  ...
finally FreeAndNil(x); end;
gabr
yes I also prefer redundent begins and ends. It just makes it clearer. I do sometimes have to deal with code such as for i := 0 to 20 do with List[i] do try finally end;It's as if it's a competition to write code with the least number of begin and ends.
Steve
+2  A: 

I used to use a "dangling" begin in Delphi:

if (SomeCondition) then begin
  ...
end;

Oddly enough, I didn't with C, because I found this more readable:

if (SomeCondition)
{
  ...
}

After a while, I stopped trying to save a single line here and there in favour of readability:

if (SomeCondition) then 
begin
  ...
end;

I also use explicit begin/end blocks where I think it improves readability. I don't need to be "clever". I need to be able to follow the intent of the code at a glance. More importantly, so does everyone who might read/maintain it.

if x = y then 
begin
  ...
  ...
end
else
begin
  for i := 0 to 20 do 
  begin
    ...
    ...
  end;
end;

I usually don't bother if there is obviously a single statement

if (SomeCondition) then
  ...
Bruce McGee
+2  A: 

See Object Pascal Style Guide.

In compound if statements, put each element separating statements on a new line: Example:

  // INCORRECT
  if A < B then begin
    DoSomething; 
    DoSomethingElse;
  end else begin
    DoThis;
    DoThat;
  end;

  // CORRECT
  if A < B then 
  begin
    DoSomething; 
    DoSomethingElse;
  end 
  else 
  begin
    DoThis;
    DoThat;
  end;
eed3si9n
You see maybe that's why I prefer the 'correct' one above, I may have been weaned on this guide! Actually, it's probably the fact I have a read a lot of the VCL source, which does to a degree follow that guide!
Steve
I've used both and just find the "correct" example to be more readable and easier to follow at a glance.
Bruce McGee
FTR: I find both of them butt-ugly. ;)The first for its poor readability, the second for its cluttering of keywords along the leftmost column.I use an extra indent for my begin/end blocks.
Oliver Giesen
A: 

Personally, I prefer to compress joining statements on one line. E.g. end else on one line. Makes it clearer that the next block of statements is related to the current one.

Brian
+2  A: 

I tend to do this in Delphi:

if a=b then begin
  c;
end else begin
  d;
end;

if x=y then z;

simply because I find it more readable than with the extra line breaks. Obviously, if I'm working with others, I'll use whatever standards we agree upon (or whatever the current code base uses), but when I'm the only one who's working on it (as in, personal projects), then I do it like this.

Michael Madsen
I fully like your first statement example, the compact format and the good use of indentation makes it much easier to read.Conserning the "if x=y then z", I only write like this when z is very simple. Most often I write z on the next line with indentation.
mliesen
I think this is very hard to read...
Andreas Rejbrand
+1  A: 

Standard in the C world is to align closing braces with either the starting statement:

if (I am nuts) {
    Psychiatry
}

or even put the opening brace on its own line:

if (I am nuts)
{
    Psychiatry
}

In some styles, the braces have different indentation:

if (I am nuts)
  {
    Psychiatry
  }

or even

if (I am nuts)
    {
    Psychiatry
    }

I used the first style for a long time in Perl, and this was my way for the else continuation:

if (I am nuts) {
    Psychiatry
  } else {
    I am free
}

but after having been exposed to Lisp, I see no additional value from putting the braces on their own line when I am already indenting properly:

if (I am completely nuts) {
    Psychiatry }
  else {
    I am free }

I have no hope to change the traditional C ways with these thoughts, though.

As an aside note, Python has thrown out the braces altogether and relies only on indentation, however this is going too far in my humble opinion, as it leads to such ridiculous things like that lambda can have only one statement.

Svante
A: 

Somebody posted that they would write the following :

if x=y then z;

Now this I really don't like, and it's got nothing to do with aesthetics. Lets assume that x,y and z are functions, If I'm stepping through the code, the above means I cannot step over x and y, and step into z.

1   if x=y then
2     Z;

I can now step into line 2 without stepping into line 1.

Steve
That would have been me, and I agree *if* they all are functions and it doesn't make sense to just use a breakpoint at the beginning of Z. However, in my code, that has usually not been the case (it's usually variables in the if-part), and so I tend to favor the single-line approach.
Michael Madsen
I like to keep it consistent though, and even if they were variables, instead of having to put a conditional breakpoint if you want to stop on that line if x=y, wheras if they were on two lines, it's a simple breakpoint.
Steve
A: 

I always line up the Begin/Ends as in your example. (Except I'd have a Begin/End around the For statement as well - just in case you go add code later.)

Anyway, if your code is multiple levels deep, then it doesn't really matter where you put your begin/end as it's too complicated. If you find yourself over, say, 3 levels deep, stop, and simplify. Create sub routines to clean things up.

CodeComplete is the best book of reference on this exact sort of thing. If you don't learn something reading that book, then I'll eat my hat.

Darian Miller
absolutely agree with the point about too deep nesting!!
Steve
A: 

Some time ago I used

if <cond> then
  begin
  ShowMessage('balablala');
  exit;
  end;

But not I folow the standart by the

if <cond> then
begin
  ShowMessage('balablala');
  exit;
end;

As in Object Pascal Style Guide

Fabricio Araujo
+1  A: 

I tend to always line up my IF and ELSE and indent my BEGIN/END block. If I have a multiple condition IF, I break that into multiple lines. If I find my self getting to deep, then I rethink what I'm coding or refactor into multiple methods. So my code looks like the following:

if condition1 then
  begin
    // do something
  end
else // not condition1
  begin
    // do something else
  end;

or the more complex if conditionals.

if condition1 or
  condition2 or
  condition3 and
  ( condition4 or
    condition5 )
then
  begin
    // do something
  end
else // not conditions
  begin
    // do something else
  end;
skamradt
A: 

This is all pretty funny. I have my own idiosyncratic way of alignment that, oddly, I use in several languages, including Pascal, C, and even COBOL (though not in a long time for that one).

I think I first saw it in a class from Ken Orr. My version is also very much like having an offside rule (similar to Python and F#) where you could just use indenting to show nesting.

Anyhow, here is how I do the example:

begin  if x = y 
       then begin (* stack to avoid getting too much indentation *)
            ...     
            ...  
            end  
       else for i := 0 to 20 
             do begin      
                ...      
                ...    
                end;
       end;

and yes, the C/C++/Java/C# flavor would be something like

  {  if (x == y)
          {  ...   /* Space as if 'then' is there */  
             ...  
             }
     else for (int i = 0; i<21; i++)
              {  ... /* space as if 'do' is there */
                 ...  
                 }
     }

I use this a lot. You could stack { and } the same way I did begin and end, but I find it more pleasing to be able to sight down an edge and confirm matching brackets and ending of the indented group. I vary to keep indenting from being excessive and to avoid having too many "{" and "}" standing alone in a sea of whitespace.

I don't evangelize this. No one has complained about being able to read it. Putting "{" on the end of a line seems like a hold-over from Ratfor pre-processors and such, sort of the way Python requires the (more-pleasant) ":" in places. I don't want to have to scan ragged right-edge down the code when I can use alignment on the left edges more usefully.

As we say around here, YMMV

orcmid
A: 

Use some code formatter like JEDI Code Format from http://jedicodeformat.sourceforge.net/

A: 

Even if it's a single statement within if, I always use compound begin-end to prevent future confusion.
Also I put // if after each end;.

if A < B then 
begin
  DoSomething; 
end; // if

Same thing for other statements:

with qryTemp do
begin
  First;

  while not Eof do
  begin
    if (A < B)
      or (C < D)
    begin
      DoSomething;
    end else
    begin
      DoSomethingElse;
    end; // if-else        

    Next;
  end; // while
end; // with

For C#, I follow Code Conventions for the Java Programming Language style compound statements.

if (condition) {
 statements;
} // if

if ((condition1 && condition2)
  || (condition3 && condition4)
  ||!(condition5 && condition6)) {
 doSomethingAboutIt();
} else {
 doSomethingElse();
} // if-else

For both Delphi and C#, the connecting logical operators come at the beginning of the next line.

eed3si9n
A: 

I`m a weekend programmer so, being the only one working on the projects i can afford not to follow a specific coding convention, lucky me.

When it comes to code readability Castalia's structural highlighting is very useful. CnPack has a similar feature is i`m not mistaking.

Alin Sfetcu
A: 

Hah! Take this! ;)

try
  if Condition1
  or (    Condition2
      and Condition3) then
    begin
      DoSomething
      DoSomeMore;
    end

  else if Condition4 then // I only do this if the nested "if" has "case"-like characteristics
    begin                 // otherwise the if would obviously be indented and on its own line
      DoSomethingElse;

      if Condition5 then
        begin
          DoThisToo;
          DoFoo;
        end;
    end

  else
    DoTheWholeShebang;

  case Whatever of
    A: DoIt;

    B, C, D:
      begin
        DoSomethingSlightly;
        MoreComplicated;
      end;

  else
    begin
      DoWhatever;
      DoLastResort; 
    end;
  end;
except
  on ESomeException do
    begin
      HandleIt;
      raise;
    end;
  on ESomeOtherException do
    DealWithIt;

  else
    DoWhateverItTakes;
end;

Strangely though, when writing in curly braces languages I also prefer the trailing brace layout:

if (condition) {
  doSomething;
} else {
  doSomethingElse;
}
Oliver Giesen
A: 

Just let your IDE indent for you in most cases.

J. Pablo Fernández
A: 

I find the code more readable when the key words (key both syntactically and logically) are exposed as much as possible.

This is so much important to me that sometimes I resort to (IMO) quite unconventional thing.

Here's what it gets like:

if (condition) then begin
  statement;
  ...
  statement; end
else begin
  ...
end;

I admit, this can make it a bit less convenient to modify the code. It's just that I find the 'dangling' end in the middle of an if statement, and aligned same as the if, somewhat confusing. If it is end, it must be the final one (for the statement), otherwise I expect either else or the beginning of the next statement at that position.

And I usually do not let it be when the then block is compound, but the else one is a single statement. This is never big deal with me to invert the condition and rearrange the blocks. Even more so since I am quite tight-fisted when it comes to wrapping a single statement with begin ... ends. In my view and experience, abundant 'begin-end's are redundant 'begin-end's more often than not. Though I like it when a statement has an explicit ending keyword, so case and repeat are my all-time favourites. :)

One more thing about ifs (and whiles for that matter) is that in case of an umpteen-decker condition I tend to place then (do) on the next line and aligned on the statement's starting key word.

Like this:

if (some_long_conditional_expression) or
   (some_other_long_conditional_expression) or
   (some_even_longer_conditional_expression)
then
  Exit;

Also, there are some other things already mentioned here which I am no foreigner to, like single-lined else ifs (when appropriate) or for ... do with ... do trys (yeah, this again may have something to do with my tight-fisting nature mentioned above).

On the whole, I might probably be too much relying on code highlighting and indentation, especially the latter. Maybe if it were not for indentation, I would prefer always to single out the begins.

Another point: someone's formatting style may very likely be caused by their programming style. Like, some people hate very big routines and tend to factor whenever possible, while others prefer to concentrate on the code itself and never mind those several screen spanning compound blocks - I find these to be very different approaches, which can result in differrent formatting habits.

Andriy M