如何在Delphi和C#中格式化复合语句?

时间:2022-05-24 08:51:16

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

作为Pascal和Delphi很长一段时间的开发人员,我总是将我的开头和结尾排成一行:

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?

当我开始使用c#时,我发现自己也在对齐花括号。 C#世界的常态是什么?

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.

有人指出,这是一个不应该在SO上提出的问题。我不明白为什么不。我正在设置编码指南文档。我知道我会对某些事情产生一些阻力,我希望能在这里得到一些答案,所以我可以随时准备迎接这种阻力。

19 个解决方案

#1


6  

I personally use:

我个人使用:

if Condition then
begin
  DoThis;
end else
begin
  DoThat;
end;

See Object Pascal Style Guide.

请参见对象Pascal样式指南。

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

在复合if语句中,将每个元素分隔语句放在一个新行上:示例:

// 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;

Here are a few more variations that are considered valid:

以下是一些被认为有效的变体:

// CORRECT
if Condition then
begin
  DoThis;
end else
begin
  DoThat;
end;

// CORRECT
if Condition then
begin
  DoThis;
end
else
  DoSomething;

// CORRECT
if Condition then
begin
  DoThis;
end else
  DoSomething;

#2


4  

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

我曾经在Delphi中使用“悬空”开头:

if (SomeCondition) then begin
  ...
end;

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

奇怪的是,我没有使用C,因为我发现它更具可读性:

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
  ...

#3


2  

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):

每个人都有不同的偏好。就我而言,在我学习Pascal之前,我学习了Modula-2。 Modula-2没有BEGIN关键字,每个块都有一个必需的END。因此代码可能看起来像这样(Modula-2恰好与大写关键字区分大小写):

IF x = y THEN
    ....
END;

When I started to code in Pascal, this became:

当我开始在Pascal中编码时,这变为:

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.

通过这种方式,代码看起来更像我以前看到的,同时仍然在可接受的Pascal代码范围内。

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.

对我来说,这些早期的印象影响了我所喜爱的几乎所有其他语言的首选括号和缩进样式。对于C#代码,没有任何特定的“规范”,就像C或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.

要遵循的唯一真正规则是:在处理现有代码时,请使用已存在的样式。处理新代码时,请使用您喜欢的样式。

#4


2  

I tend to do this in Delphi:

我倾向于在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.

只是因为我发现它比额外的换行符更具可读性。显然,如果我和其他人一起工作,我会使用我们同意的任何标准(或者当前代码库使用的任何标准),但是当我是唯一一个正在使用它的人时(如个人项目),那么我是这样做的。

#5


1  

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

C世界的标准是将结束括号与起始语句对齐:

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:

我在Perl中使用了第一种风格,这是我继续使用的方式:

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:

但是在接触到Lisp之后,当我已经正确缩进时,我认为没有额外的价值可以将括号放在自己的行上:

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

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

但是,我没有希望用这些想法改变传统的C方式。

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.

顺便说一下,Python已经完全抛弃了大括号,只依赖于缩进,但是在我的拙见中这太过分了,因为它导致了像lambda只能有一个陈述这样荒谬的事情。

#6


1  

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和ELSE并缩进我的BEGIN / END块。如果我有多重条件IF,我将其分成多行。如果我发现我的自我深入,那么我重新思考我正在编码或重构多种方法。所以我的代码如下所示:

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;

#7


0  

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

之前有人问过。例如c-coding-standard-best-practices。

#8


0  

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.

有时我会使用这样的折叠(如第二种情况)来组合if和try..finally。

x := GetMeTheObject;
if assigned(x) then try
  ...
finally FreeAndNil(x); end;

#9


0  

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.

就个人而言,我更喜欢在一行压缩加入语句。例如。在一条线上结束。使下一个语句块与当前语句块相关更清楚。

#10


0  

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.

现在我真的不喜欢,这与美学无关。让我们假设x,y和z是函数,如果我单步执行代码,上面的意思是我不能跨越x和y,并进入z。

1   if x=y then
2     Z;

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

我现在可以进入第2行而不进入第1行。

#11


0  

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.)

我总是按照你的例子排列开始/结束。 (除了我在For语句周围有一个Begin / End之外 - 以防你以后再添加代码。)

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.

无论如何,如果你的代码是多层次的,那么你把你的开始/结束放在哪里并不重要,因为它太复杂了。如果你发现自己结束了,比如3级深度,停止并简化。创建子例程以清理事物。

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.

CodeComplete是关于这类事情的最佳参考书。如果你没有读到那本书,那我就会吃掉我的帽子。

#12


0  

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).

这一切都很有趣。我有自己独特的对齐方式,奇怪的是,我使用多种语言,包括Pascal,C,甚至COBOL(虽然不是很长时间)。

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.

我想我第一次在Ken Orr的课堂上看过它。我的版本也非常像有一个越位规则(类似于Python和F#),你可以使用缩进来显示嵌套。

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

是的,C / C ++ / Java / C#风味就像是

  {  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.

我不传福音。没有人抱怨能够阅读它。将“{”放在一行的末尾似乎是来自Ratfor预处理器的延续,这就像Python在某些地方需要(更令人愉快的)“:”的方式。当我可以更有用地使用左边缘上的对齐时,我不想在代码中扫描粗糙的右边缘。

As we say around here, YMMV

正如我们在这里所说,YMMV

#13


0  

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

使用http://jedicodeformat.sourceforge.net/中的一些代码格式化程序,如JEDI代码格式

#14


0  

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中的单个陈述,我总是使用复合开头来防止将来混淆。我也把//如果在每次结束之后;

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.

对于C#,我遵循Java编程语言样式复合语句的代码约定。

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.

对于Delphi和C#,连接逻辑运算符都出现在下一行的开头。

#15


0  

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.

在代码可读性方面,Castalia的结构突出显示非常有用。 CnPack有一个类似的功能是我没有错。

#16


0  

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;
}

#17


0  

Just let your IDE indent for you in most cases.

在大多数情况下,只需让您的IDE缩进即可。

#18


0  

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.

这对我来说非常重要,有时我会诉诸(IMO)非常传统的事情。

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.

我承认,这可以使修改代码变得不那么方便。只是我在if语句的中间找到'悬空'结尾,并且与if相同,有点令人困惑。如果它结束,它必须是最后一个(对于语句),否则我期望在该位置的其他或下一个语句的开头。

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. :)

当then块是复合时,我通常不会让它成为复合,但是其他的是单一的声明。对于我来说,反转条件并重新排列块并不是什么大问题。更重要的是,因为当我用开始...结束包装单个语句时,我非常紧张。根据我的观点和经验,丰富的“初始端是多余的”开端往往是。虽然我喜欢它,当一个语句有一个明确的结束关键字时,所以case和repeat是我的最爱。 :)

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.

关于ifs(以及相关问题)的另一个问题是,如果遇到一个无数的条件,我倾向于将(do)放在下一行并在语句的起始关键字上对齐。

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).

此外,还有一些其他已经提到的东西,我不是外国人,比如单行其他ifs(适当的时候)或者......做...做trys(是的,这又可能与某些事情有关)我上面提到的紧张拳击性质。

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.

另一点:某人的格式化风格很可能是由他们的编程风格引起的。比如,有些人讨厌非常大的例程并且倾向于尽可能地考虑因素,而其他人更喜欢专注于代码本身而不关心那些跨越复合块的几个屏幕 - 我发现这些是非常不同的方法,这可能导致不同的格式习惯。

#19


0  

Some time ago I used

前段时间我用过

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

But now I follow the standard by the

但现在我遵循标准

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

As in Object Pascal Style Guide

与Object Pascal样式指南中一样

#1


6  

I personally use:

我个人使用:

if Condition then
begin
  DoThis;
end else
begin
  DoThat;
end;

See Object Pascal Style Guide.

请参见对象Pascal样式指南。

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

在复合if语句中,将每个元素分隔语句放在一个新行上:示例:

// 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;

Here are a few more variations that are considered valid:

以下是一些被认为有效的变体:

// CORRECT
if Condition then
begin
  DoThis;
end else
begin
  DoThat;
end;

// CORRECT
if Condition then
begin
  DoThis;
end
else
  DoSomething;

// CORRECT
if Condition then
begin
  DoThis;
end else
  DoSomething;

#2


4  

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

我曾经在Delphi中使用“悬空”开头:

if (SomeCondition) then begin
  ...
end;

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

奇怪的是,我没有使用C,因为我发现它更具可读性:

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
  ...

#3


2  

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):

每个人都有不同的偏好。就我而言,在我学习Pascal之前,我学习了Modula-2。 Modula-2没有BEGIN关键字,每个块都有一个必需的END。因此代码可能看起来像这样(Modula-2恰好与大写关键字区分大小写):

IF x = y THEN
    ....
END;

When I started to code in Pascal, this became:

当我开始在Pascal中编码时,这变为:

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.

通过这种方式,代码看起来更像我以前看到的,同时仍然在可接受的Pascal代码范围内。

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.

对我来说,这些早期的印象影响了我所喜爱的几乎所有其他语言的首选括号和缩进样式。对于C#代码,没有任何特定的“规范”,就像C或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.

要遵循的唯一真正规则是:在处理现有代码时,请使用已存在的样式。处理新代码时,请使用您喜欢的样式。

#4


2  

I tend to do this in Delphi:

我倾向于在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.

只是因为我发现它比额外的换行符更具可读性。显然,如果我和其他人一起工作,我会使用我们同意的任何标准(或者当前代码库使用的任何标准),但是当我是唯一一个正在使用它的人时(如个人项目),那么我是这样做的。

#5


1  

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

C世界的标准是将结束括号与起始语句对齐:

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:

我在Perl中使用了第一种风格,这是我继续使用的方式:

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:

但是在接触到Lisp之后,当我已经正确缩进时,我认为没有额外的价值可以将括号放在自己的行上:

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

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

但是,我没有希望用这些想法改变传统的C方式。

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.

顺便说一下,Python已经完全抛弃了大括号,只依赖于缩进,但是在我的拙见中这太过分了,因为它导致了像lambda只能有一个陈述这样荒谬的事情。

#6


1  

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和ELSE并缩进我的BEGIN / END块。如果我有多重条件IF,我将其分成多行。如果我发现我的自我深入,那么我重新思考我正在编码或重构多种方法。所以我的代码如下所示:

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;

#7


0  

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

之前有人问过。例如c-coding-standard-best-practices。

#8


0  

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.

有时我会使用这样的折叠(如第二种情况)来组合if和try..finally。

x := GetMeTheObject;
if assigned(x) then try
  ...
finally FreeAndNil(x); end;

#9


0  

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.

就个人而言,我更喜欢在一行压缩加入语句。例如。在一条线上结束。使下一个语句块与当前语句块相关更清楚。

#10


0  

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.

现在我真的不喜欢,这与美学无关。让我们假设x,y和z是函数,如果我单步执行代码,上面的意思是我不能跨越x和y,并进入z。

1   if x=y then
2     Z;

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

我现在可以进入第2行而不进入第1行。

#11


0  

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.)

我总是按照你的例子排列开始/结束。 (除了我在For语句周围有一个Begin / End之外 - 以防你以后再添加代码。)

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.

无论如何,如果你的代码是多层次的,那么你把你的开始/结束放在哪里并不重要,因为它太复杂了。如果你发现自己结束了,比如3级深度,停止并简化。创建子例程以清理事物。

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.

CodeComplete是关于这类事情的最佳参考书。如果你没有读到那本书,那我就会吃掉我的帽子。

#12


0  

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).

这一切都很有趣。我有自己独特的对齐方式,奇怪的是,我使用多种语言,包括Pascal,C,甚至COBOL(虽然不是很长时间)。

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.

我想我第一次在Ken Orr的课堂上看过它。我的版本也非常像有一个越位规则(类似于Python和F#),你可以使用缩进来显示嵌套。

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

是的,C / C ++ / Java / C#风味就像是

  {  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.

我不传福音。没有人抱怨能够阅读它。将“{”放在一行的末尾似乎是来自Ratfor预处理器的延续,这就像Python在某些地方需要(更令人愉快的)“:”的方式。当我可以更有用地使用左边缘上的对齐时,我不想在代码中扫描粗糙的右边缘。

As we say around here, YMMV

正如我们在这里所说,YMMV

#13


0  

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

使用http://jedicodeformat.sourceforge.net/中的一些代码格式化程序,如JEDI代码格式

#14


0  

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中的单个陈述,我总是使用复合开头来防止将来混淆。我也把//如果在每次结束之后;

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.

对于C#,我遵循Java编程语言样式复合语句的代码约定。

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.

对于Delphi和C#,连接逻辑运算符都出现在下一行的开头。

#15


0  

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.

在代码可读性方面,Castalia的结构突出显示非常有用。 CnPack有一个类似的功能是我没有错。

#16


0  

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;
}

#17


0  

Just let your IDE indent for you in most cases.

在大多数情况下,只需让您的IDE缩进即可。

#18


0  

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.

这对我来说非常重要,有时我会诉诸(IMO)非常传统的事情。

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.

我承认,这可以使修改代码变得不那么方便。只是我在if语句的中间找到'悬空'结尾,并且与if相同,有点令人困惑。如果它结束,它必须是最后一个(对于语句),否则我期望在该位置的其他或下一个语句的开头。

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. :)

当then块是复合时,我通常不会让它成为复合,但是其他的是单一的声明。对于我来说,反转条件并重新排列块并不是什么大问题。更重要的是,因为当我用开始...结束包装单个语句时,我非常紧张。根据我的观点和经验,丰富的“初始端是多余的”开端往往是。虽然我喜欢它,当一个语句有一个明确的结束关键字时,所以case和repeat是我的最爱。 :)

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.

关于ifs(以及相关问题)的另一个问题是,如果遇到一个无数的条件,我倾向于将(do)放在下一行并在语句的起始关键字上对齐。

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).

此外,还有一些其他已经提到的东西,我不是外国人,比如单行其他ifs(适当的时候)或者......做...做trys(是的,这又可能与某些事情有关)我上面提到的紧张拳击性质。

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.

另一点:某人的格式化风格很可能是由他们的编程风格引起的。比如,有些人讨厌非常大的例程并且倾向于尽可能地考虑因素,而其他人更喜欢专注于代码本身而不关心那些跨越复合块的几个屏幕 - 我发现这些是非常不同的方法,这可能导致不同的格式习惯。

#19


0  

Some time ago I used

前段时间我用过

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

But now I follow the standard by the

但现在我遵循标准

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

As in Object Pascal Style Guide

与Object Pascal样式指南中一样