功能多与少
我有一点争论,想知道人们的想法:
在 C++(或一般情况下)中,您是否更喜欢将代码分解为许多较短的函数,其中 main() 仅包含按逻辑顺序的函数列表,还是您更喜欢仅在必要时使用函数(即,当它们会被重用很多次时)?或者也许介于两者之间?
I had a little argument, and was wondering what people out there think:
In C++ (or in general), do you prefer code broken up into many shorter functions, with main() consisting of just a list of functions, in a logical order, or do you prefer functions only when necessary (i.e., when they will be reused very many times)? Or perhaps something in between?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(8)
我更喜欢适合一屏代码的函数(或方法),因此我可以一目了然地看到我需要引用的任何内容以了解该函数的工作原理。我的编辑器窗口中通常有大约 50 行空间,通常也有 80 列,因此我可以在监视器上并排放置两行,并在两段代码之间交叉引用。
因此,我通常认为 50 行左右是最大值。我唯一会考虑允许更多的是当你有一个大的长初始化函数或完全线性的函数(没有变量、条件或循环)时,因为这不是你需要那么多上下文的东西,而且有些 API 需要整个一堆初始化来启动和运行,并将其分成更小的函数并没有多大帮助。
不过,总的来说,漂亮、小、易于理解、只做一件事并且命名良好的函数比那些长达数百行、需要跟踪数十个变量、缩进深度达 10 级的庞然大物要好得多。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
小功能,请
传统观点认为功能越小越好,我认为这是事实。事实上,有一家公司拥有一种分析工具,可以通过与单元测试数量相比做出的决策数量来对各个功能进行评级。
理论上,您可能无法降低整个应用程序的复杂性,但您可以完全控制任何给定函数的复杂性。
一种名为圈复杂度的测量被认为与不良代码呈正相关...具体来说,通过一个方法的路径越多,它的 CCN 编号就越高,它写得越差,就越难理解,因此越难改变,甚至越难开始,单元测试就越多会需要。
好的,找到工具了。它被称为,嗯,Change R风险分析和P预测指数。
最近,“信息只编码一次”的原则出现了新的缩写词,特别是 DRY (不要重复自己)和DIE(重复是邪恶的) ...
我相信我们可以部分感谢 RoR 社区推广这一理念......
Small functions, please
It is the conventional wisdom that smaller functions are better, and I think it's true. In fact, there is a company with an analysis tool that rates individual functions by how many decisions they make compared to the number of unit tests that they have.
The theory is that you may or may not be able to reduce complexity in an entire application, but you have complete control over how much complexity is in any given function.
A measurement called cyclomatic complexity is thought to correlate positively with bad code...specifically, the more paths there are through a method the higher its CCN number is, the more poorly it is written, the harder it is to understand and hence change or even get right to start with, and the more unit tests it will need.
Ok, found the tool. It is called, ahem, the Change Risk Analysis and Predictions index.
Lately, the principle of encoding information only once has grown new acronyms, specifically DRY (Don't Repeat Yourself) and DIE (Duplication is Evil) ...
I believe we can in part thank the RoR community for promoting this philosophy...