如果你打破了长代码行,你如何缩进下一行的内容?

发布于 2024-07-16 00:42:16 字数 1704 浏览 5 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

も星光 2024-07-23 00:42:16

我喜欢在自己的行上放置大括号,因为我觉得更容易将条件和内部块全部视为一项(如果您知道我的意思):

if ((long test 1)
    && (long test 2)
    && (long test 3)) 
{
    code executed if true;
}

并且我喜欢以条件是什么开始附加条件行,因为我发现“ join”条件非常重要,但在上一行的末尾往往会被忽视。

我还尝试缩进,以使括号的效果显而易见(尽管尝试避免长条件句通常是一件好事)。

我尝试构建一些东西,以便我可以轻松地“扫描”“东西”:)

I like braces on their own line because I fine it easier to see the condition and inner block all as one item (if you know what I mean):

if ((long test 1)
    && (long test 2)
    && (long test 3)) 
{
    code executed if true;
}

and I like starting additional conditional lines with what the condition is because I find that the "joining" condition is very important and it tends to get overlooked at the end of the previous line.

I also try and indent such that the effect of parenthesis are obvious (though trying to avoid long conditionals is generally a good thing).

I try and structure stuff so that I can easily "scan" for "stuff" :)

瑶笙 2024-07-23 00:42:16

您应该尝试防止编写超过 80 个字符的行,而不是破坏它们:

  • 尝试通过转换条件和封装代码来尽量减少缩进。

Linus Torvalds:如果您需要超过 3 个级别
缩进,无论如何你都被搞砸了,
并且应该修复你的程序。

除了条件是您封装的其他内容已准备好在其他地方使用之外,这还有一个副作用,使您的代码更具可读性。

bool encapsulatedLongCondition() // Add some parameters
{
  if (!condition1)
    return false;

  if (!condition2)
    return false;

  // ... (Other conditions)

  return true;
}    

if (encapsulatedLongCondition())
{
  // ... (Call some methods, try not to introduce deeper if/loop levels!)
}

通过布尔代数简化条件并尝试反转条件和返回值会很有帮助。 :-)

另请参阅:你能简化这个算法吗?
另请参阅 2:Refactor for C# 能够帮助您完成此任务。 ;-)

  • 使用类型定义并尽量避免长名称

一个简单的例子,想象一下在另一个容器中使用没有 typedef 且名称较长的 Days 会花费多长时间。

struct Day
{
  // Some data
};
struct Event
{
  // Some data
};
typedef list<Event> Events;
typedef map<Day, Event> Days;
// Some other container that would else be long...
  • ...(您应该尝试分析为什么您的行很长并找到解决方案)

希望您能了解总体思路,这样您就不需要提出肮脏的换行符。 ;-)

我会看到长行出现的唯一地方是在函数的原型中,或者在调用它们时,您应该尝试在最后一个可能的逗号后中断并继续下一行。 而不是在每个之后执行此操作并浪费多行,使滚动变得臃肿并且您的函数过于突出...如果您碰巧经常看到这些长行,您可以将返回类型放在函数名称之前的行上。

void longFunctionName(ParameterType1 parameter1, ParameterType2 parameter2,
                      ParameterType3 parameter3, ParameterType4 parameter4)  

You should try to prevent writing lines longer than 80 characters rather than breaking them:

  • Try to minimize indentation by converting conditions and encapsulating code.

Linus Torvalds: If you need more than 3 levels of
indentation, you're screwed anyway,
and should fix your program.

This also has the side effect of making you code much more readable, besides that the conditions are the other things you encapsulate are ready to be used elsewhere.

bool encapsulatedLongCondition() // Add some parameters
{
  if (!condition1)
    return false;

  if (!condition2)
    return false;

  // ... (Other conditions)

  return true;
}    

if (encapsulatedLongCondition())
{
  // ... (Call some methods, try not to introduce deeper if/loop levels!)
}

Simplifying your condition through boolean algebra and trying to invert the condition and return value can help a lot. :-)

See also: Can you simplify this algorithm?
See also 2: Refactor for C# has the ability to assist you with this. ;-)

  • Use type definitions and try to avoid long names

A simple example, imagine how long it would be using Days without typedef with longer names in another container.

struct Day
{
  // Some data
};
struct Event
{
  // Some data
};
typedef list<Event> Events;
typedef map<Day, Event> Days;
// Some other container that would else be long...
  • ... (You should try to analyze why your line is long and find a solution for it)

Hope you get the general idea, this way you won't need to come up with a dirty line break. ;-)

The only place where I would see long lines occur is in the prototypes of your functions or when calling them, there you should just try to break after the last possible comma and continue on the next line. Rather than doing it after each and wasting multiple lines making scrolling bloated and your function stand out too much... You could place the return type on the line before the function name if you happen to frequently see these long lines.

void longFunctionName(ParameterType1 parameter1, ParameterType2 parameter2,
                      ParameterType3 parameter3, ParameterType4 parameter4)  
枫林﹌晚霞¤ 2024-07-23 00:42:16

一般来说,我这样做:

if (condition) {
     something;
}

对于块分隔符。 但是,如果我必须分解长行的情况,我会使用以下内容:与

if (
    (long test 1) &&
    (long test 2) &&
    (long test 3)
) {
    code executed if true;
}

rbobby 的答案的主要区别:

  1. 每行末尾的运算符而不是后续行的开头,以非常清楚地直观地表明该行不完整
  2. 第一行在条件元素之前换行——这有助于保持代码“形状”一致。
  3. 右括号不缩进。

这具有使参数/条件列表看起来有点像代码块的视觉效果(但用括号而不是大括号。我发现对称性令人愉悦。它还避免了在一行上有一个裸露的大括号(我认为这看起来很糟糕) 。

In general I do:

if (condition) {
     something;
}

for block delimiters. However, if the case of a long line I have to break up, I use this:

if (
    (long test 1) &&
    (long test 2) &&
    (long test 3)
) {
    code executed if true;
}

Key differences from rbobby's answer:

  1. Operators at the end of each line instead of the beginning of subsequent lines, to very clearly indicate visually that the line is incomplete
  2. Line break on first line before conditional element -- this helps keep code "shape" consistent.
  3. Closing paren not indented.

This has the visual effect of making parameter/conditional lists look kinda like code blocks (but with parens instead of curly braces. I find the symmetry pleasing. It also avoids having a bare opening curly brace on a line (which I think looks terrible).

辞取 2024-07-23 00:42:16

我有两个简单的规则:

  1. 语句块:一个缩进;
  2. 行延续:两个缩进或括号对齐,无论进一步缩进。

所以,在 if 情况下:

if ((long test 1) &&
        (long test 2) &&
        (long test 3)) {
    code executed if true;
}

I have two simple rules:

  1. Statement block: one indentation;
  2. Line continuation: two indentations or parenthesis aligned, whatever is further indented.

So, in the if case:

if ((long test 1) &&
        (long test 2) &&
        (long test 3)) {
    code executed if true;
}
挖鼻大婶 2024-07-23 00:42:16

我对这里已经写的内容略有不同:

if ((long test 1) &&
    (long test 2) &&
    (long test 3)) 
{
    code executed if true;
}

我喜欢将布尔运算符放在行尾。

长方法名,或者有很多参数的方法是这样的:

reallyLongMethodName (paramA,
                      paramB,
                      paramC);

位与上面的参数名对齐; 不是括号...

另外,为了减少缩进,我开始在代码中使用多个返回点,以及循环中的继续和中断。 例如

for(int i = 0; i < MAX; i++)
{
    if(!isPrime(i)) // predefined prime finding func
        continue;

    //now we have only prime values of i
}

I have a slight variation on what's already written here:

if ((long test 1) &&
    (long test 2) &&
    (long test 3)) 
{
    code executed if true;
}

I like having my boolean operators at the end of the line.

Long method names, or methods with lots of parameters are like this:

reallyLongMethodName (paramA,
                      paramB,
                      paramC);

with the bits lined up with the param name above; not the bracket...

Also, to reduce indentation, I've started using multiple return points in my code, as well as continues and breaks in my loops. eg

for(int i = 0; i < MAX; i++)
{
    if(!isPrime(i)) // predefined prime finding func
        continue;

    //now we have only prime values of i
}
始终不够 2024-07-23 00:42:16

我支持,“不要与 IDE 作对。”

然而,我的 IDE(Eclipse、Visual Studio)想要打破界限,这就是它们的打破方式。

这可能意味着语言之间存在不一致,但这没关系。

I side with, "Don't fight the IDE."

However my IDE (Eclipse, Visual Studio) wants to break lines is how they are broken.

This may mean inconsistencies between languages, which is OK.

甜尕妞 2024-07-23 00:42:16

总是缩进,但 if 语句很特殊; 我喜欢排列测试,并将额外的 && 运算符放在左侧:

if (  (long test 1)
   && (long test 2)
   && (long test 3)) 
{
    code executed if true;
}

&& 拉到左侧以与 对齐>if 也是可能的,但我发现这个替代方案更难阅读。

Always indent, but if statements are special; I like to line up the tests, and I put the extra && operators on the left:

if (  (long test 1)
   && (long test 2)
   && (long test 3)) 
{
    code executed if true;
}

Pulling the && to the left to align with if is also possible, but I find this alternative harder to read.

山色无中 2024-07-23 00:42:16

使用 astyle 或任何您正在使用的自动压头。 它似乎做得足够好,通常还有更重要的事情需要考虑。

With astyle, or whatever automatic indenter you're using. It seems to do a good enough job, and there usually are more important things to think about.

も让我眼熟你 2024-07-23 00:42:16

我将括号内的表达式保留在其开头的级别:

if ((long test 1) &&
    (long test 2) &&
    (long test 3)) {
  code executed if true;
}

这使得每个表达式所处的级别变得显而易见。

I keep bracketed expressions at the level of their opening:

if ((long test 1) &&
    (long test 2) &&
    (long test 3)) {
  code executed if true;
}

This makes it obvious which level each expression is at.

呢古 2024-07-23 00:42:16

我想说,只要满足以下条件,使用什么方法并不重要:

  • 是明智的
  • 在整个代码中应用相同的约定

。 如果您参与团队开发,如果您无法达成一致并且没有人可以发号施令,请尝试通过某种神秘的投票机制在你们之间达成一项约定。

I'd say it doesn't really matter what method you use providing it meets the following criteria:

  • it is sensible
  • you apply the same convention throughout your code.

If you're in a team development, do try to agree on a convention between you, by some arcane voting mechanism if you can't reach agreement otherwise and there's no-one to dictate.

诗酒趁年少 2024-07-23 00:42:16

以特定方式格式化代码的唯一原因是使其可读。 这本质上是主观的——以一种看起来不错的方式来做,并且你觉得对于第一次查看代码的人来说更具可读性。 我要反驳传统观点并说,不要担心任何共同标准 - 原因有两个

1)在这种情况下很难,因为断线有很多不同的可能性

2)它不会给你买任何东西。 时期。 再次强调,代码格式化只是为了使代码可读,采用标准方法格式化代码细节并不能为您带来可读性。

The only reason for formatting code in a particular way is to make it readable. This is inherently subjective - do it in a way that looks good and that you feel would be more readable for someone looking at the code for the first time. And I'm going to buck the conventional wisdom and say, don't worry about any common standard - for two reasons

1) it's difficult in this situation, because there are so many different possibilities for broken lines

2) it doesn't buy you anything. period. again, code formatting is simply to make your code readable, having a standard way of formatting the particulars of your code does not buy you readability.

胡渣熟男 2024-07-23 00:42:16

在我看来,78 或 80 个字符的行宽很有用,因为它可以更轻松地在同一屏幕上并排打开多个文件。

理由,Linus Torvalds 的引用怎么样? :)

答案是如果你需要
超过 3 级压痕,
无论如何你都被搞砸了,应该修复
你的程序。

我通常遵循 Google C++ 编码风格(您可以我想也将其适应 Java)和这种 C++ 编码风格

In my opinion, a line width of 78 or 80 characters is useful since it makes it easier to have multiple files open next to each other on the same screen.

Justification, what about a quote by Linus Torvalds? :)

The answer to that is that if you need
more than 3 levels of indentation,
you're screwed anyway, and should fix
your program.

I normally follow a conglomerate of the Google C++ coding style (you can adapt this to Java, too, I guess) and this C++ coding style.

追我者格杀勿论 2024-07-23 00:42:16

我几乎从不在同一行缩进。 但是,我很少会重新初始化一堆这样的变量。

a 
= b
= c
= d
= e
= f
= 0;

不过,执行此类操作的一个关键是将赋值运算符保留为下一行的第一个字符。 这将给予维护。 当程序员看到它时,他们会感到很糟糕,迫使他们去看,而不仅仅是掩盖它。

包装一个很长的声明,我会在我认为有意义的地方这样做......不一定是在第一个缩进。 所以 :

reallyLongMethodName (paramA,paramB,paramC);

不会被格式化,

reallyLongMethodName (paramA,
    paramB,
    paramC);

但最终会更像

reallyLongMethodName (paramA,
                    paramB,
                    paramC);

所有参数都与左括号对齐。

对于 if 和 while,我会做类似的事情

if((long test 1) 
&& (long test 2) 
&& (long test 3))
{
    code executed if true;
}

I almost never indent on the same line. However, I have on very rare ocassion re-initialize a bunch of variables like this

a 
= b
= c
= d
= e
= f
= 0;

The one key thing with doing something like this though, is to keep the assignment operator as the first character on the next line. This will give the maint. programmer a WTF moment when they see it, forcing them to look at, not just gloss over it.

Wrapping a very long statement, I'll do it where ever I feel it makes sense ... not necessarily on the first indent. So :

reallyLongMethodName (paramA,paramB,paramC);

would not get formatted like

reallyLongMethodName (paramA,
    paramB,
    paramC);

but would end up more like

reallyLongMethodName (paramA,
                    paramB,
                    paramC);

with all the parameters lining up with the opening parenthesis.

For if's and whiles, I'd do something like

if((long test 1) 
&& (long test 2) 
&& (long test 3))
{
    code executed if true;
}
梦回旧景 2024-07-23 00:42:16

对于 Java,Oracle 提供了这些约定。 Java 代码约定 - Oracle。

  • 逗号后换行
  • 运算符前换行
  • 优先选择较高级别的换行符而不是较低级别的换行符
  • 将新行与上一行同一级别的表达式的开头对齐
  • 如果上述规则导致代码混乱或代码被压缩到右边距,只需缩进 8例如

longName1 = longName2 * (longName3 + longName4 - longName5)
            + 4 * longname6; // PREFER
longName1 = longName2 * (longName3 + longName4
                        - longName5) + 4 * longname6; // AVOID

另一个:

//DON’T USE THIS INDENTATION
if ((condition1 && condition2)
    || (condition3 && condition4)
    ||!(condition5 && condition6)) { //BAD WRAPS
    doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS
}
//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
        || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();
}
//OR USE THIS
if ((condition1 && condition2) || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();
}

该文档中给出了更多示例。

For Java Oracle provides those conventions. Java Code Conventions - Oracle.

  • Break after a comma
  • Break before an operator
  • Prefer higher-level breaks to lower-level breaks
  • Align the new line with the beginning of the expression at the same level on the previous line
  • If the above rules lead to confusing code or to code that’s squished up against the right margin, just indent 8 spaces instead

For an example,

longName1 = longName2 * (longName3 + longName4 - longName5)
            + 4 * longname6; // PREFER
longName1 = longName2 * (longName3 + longName4
                        - longName5) + 4 * longname6; // AVOID

Another :

//DON’T USE THIS INDENTATION
if ((condition1 && condition2)
    || (condition3 && condition4)
    ||!(condition5 && condition6)) { //BAD WRAPS
    doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS
}
//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
        || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();
}
//OR USE THIS
if ((condition1 && condition2) || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();
}

More examples are given in that document.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文