代码格式:排列类似的行好吗? [英] Code formatting: is lining up similar lines ok?

查看:31
本文介绍了代码格式:排列类似的行好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现我们公司有一套编码指南(隐藏在一个没人能找到的文档管理系统中).它通常看起来很明智,并且避免了关于在哪里放置 '{' 以及是否使用硬制表符的常见宗教战争.但是,它确实表明行不应该包含嵌入的多个空格".这意味着不要做这种事情:

I recently discovered that our company has a set of coding guidelines (hidden away in a document management system where no one can find it). It generally seems pretty sensible, and keeps away from the usual religious wars about where to put '{'s and whether to use hard tabs. However, it does suggest that "lines SHOULD NOT contain embedded multiple spaces". By which it means don't do this sort of thing:

foo    = 1;
foobar = 2;
bar    = 3;

或者这个:

if      ( test_one    ) return 1;
else if ( longer_test ) return 2;
else if ( shorter     ) return 3;
else                    return 4;

或者这个:

thing foo_table[] =
{
  { "aaaaa", 0 },
  { "aa",    1 },
  // ...
}

这样做的理由是,对一行的更改通常需要对每一行进行编辑.这使得改变变得更加努力,并且更难理解差异.

The justification for this is that changes to one line often require every line to be edited. That makes it more effort to change, and harder to understand diffs.

我被撕裂了.一方面,像这样排列可以使重复的代码更容易阅读.另一方面,它确实使差异更难阅读.

I'm torn. On the one hand, lining up like this can make repetitive code much easier to read. On the other hand, it does make diffs harder to read.

您对此有何看法?

推荐答案

2008:由于我每天监督源代码的合并,...我只能反对它.

2008: Since I supervise daily merges of source code,... I can only recommend against it.

这很漂亮,但如果您定期进行合并,更易于阅读"的好处很快就会远远少于合并代码所涉及的工作量.

It is pretty, but if you do merges on a regular basis, the benefit of 'easier to read' is quickly far less than the effort involved in merging that code.

由于该格式无法以简单的方式自动化,因此第一个不遵循它的开发人员将触发非平凡的合并.

Since that format can not be automated in a easy way, the first developer who does not follow it will trigger non-trivial merges.

不要忘记在源代码合并中,不能要求diff工具忽略空格:
否则,"和""在差异期间看起来相同,这意味着不需要合并......编译器(以及在字符串双引号之间添加空格的编码器)不会同意这一点!

Do not forget that in source code merge, one can not ask the diff tool to ignore spaces :
Otherwise, "" and " " will look the same during the diff, meaning no merge necessary... the compiler (and the coder who added the space between the String double quotes) would not agree with that!

2020:如评论中所述 来自 Marco

大多数代码合并应该能够处理忽略空格和对齐等号现在是大多数 IDE 中的自动格式选项.

most code mergers should be able to handle ignoring whitespace and aligning equals is now an auto format option in most IDE.

我仍然更喜欢带有自己格式选项的语言,例如 Go 及其 gofmt 命令.
甚至 Rust 也有它的 rustfmt 现在.

I still prefer languages which come with their own formatting options, like Go and its gofmt command.
Even Rust has its rustfmt now.

这篇关于代码格式:排列类似的行好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆