包装代码行的公约?

时间:2010-02-03 02:20:32

标签: code-formatting textwrapping

我通常将我的代码行换行,以便它们长达80个字符。

哪种包装看起来更好?

// (A)
std::vector<MyLongClassName::size_type>* myvector
    = new std::vector<MyLongClassName::size_type>();
bool isOneOrAnother = hereIsOneLongCondition
    && hereIsAnotherOne;

// (B)
std::vector<MyLongClassName::size_type>* myvector =
    new std::vector<MyLongClassName::size_type>();
bool isOneOrAnother = hereIsOneLongCondition &&
    hereIsAnotherOne;

我知道这是武断的,但有一种约定或首选方式吗?

5 个答案:

答案 0 :(得分:2)

我选择(B),但是对于布尔值,我可能会添加不完全必要的parens然后将值放在其中。我只是添加了parens,因为没有它们我的emacs不会为我做。

bool isOneOrAnother = ( hereIsOneLongCondition &&
                        hereIsAnotherOne );

答案 1 :(得分:1)

第二种陈述的另一种可能性(有时):

bool isOneOrAnother =
   hereIsOneLongCondition && hereIsAnotherOne;

答案 2 :(得分:0)

我个人提到将任何运算符放在一行的末尾。我相信微软也推荐这种做法,但目前我找不到这个页面。然而,C# style guide here建议同样的事情......

  

当表达式不适合a时   单行,按照分手   这些一般原则:
   #逗号后打破。
   #在运营商之后休息    #更喜欢较高级别的休息时间到较低级别的休息时间    #将新行与表达式的开头对齐   上一行的相同级别。

记住,我读过的大多数代码都倾向于遵循这条规则。如果你正在寻找这背后的基本原理,我唯一可以真正提供的是,使用运算符开始一行是没有意义的,因为你有效地启动了一个新的(子)表达式,从而使它成为现实。更容易分开心理。此外,如果有人逐行读取代码,如果在当前行的末尾有一个挂起的操作符,而不是下一行的开头,则更容易注意到行继续。

希望有所帮助。

答案 3 :(得分:0)

我是另一个喜欢(B)的人,但我喜欢的第二个声明:

bool isOneOrAnother =
         hereIsOneLongCondition &&
         hereIsAnotherOne;

首选(B)的原因来自于习惯于javascript的<cough> broken </cough>分号插入语法。由于我经常在多语言环境中工作,因此我习惯会破坏我使用的一种语言。

答案 4 :(得分:0)

我是Graeme Perrow的第二个回答。在 某些 的情况下,我有类似

的情况
bool someCondition = ( hereIsOneLongCondition &&
                       hereIsAnotherOne &&
                       hereIsYetAnother &&
                       ohNoHereIsMore);

我倾向于将表达式放在函数中:

bool someCondition = Foo();

它的好处是可以更容易地编辑Foo() - 我可以评论各行:

bool Foo()
{

   bool result = true;

   if (!hereIsOneLongCondition)
   {
      result = false;
   }

   if (!hereIsAnotherOne)
   {
      // this was added to fix such-and-such bug
      result = false;
   }

   // etc

   return result;
}

上面,我说 一些 ,因为这并不总是可行的,它确实产生了更多的代码行。但是,发现错误和重构更容易。

相关问题