在可以选择的语言中,将主函数/方法/代码放在顶部还是底部更好?

发布于 2024-09-24 15:15:03 字数 1431 浏览 3 评论 0原文

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

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

发布评论

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

评论(3

慕巷 2024-10-01 15:15:03

我想这只是一个偏好问题。就我个人而言,我喜欢将它放在顶部,这样一旦打开代码,您就可以准确地看到它在做什么,然后从那里转到方法的定义。我认为这比打开文件并看到一堆随机方法然后滚动到底部查看它们实际被调用更有意义。

正如我所说,这都是偏好。要么:

function myMain(){
  methodOne();
  methodTwo();
  methodThree();
}

function methodOne(){
  //code here
}
function methodTwo(){
  //code here
}
function methodThree(){
  //code here
}

或者:

function methodOne(){
  //code here
}
function methodTwo(){
  //code here
}
function methodThree(){
  //code here
}

function myMain(){
  methodOne();
  methodTwo();
  methodThree();
}

I guess its just a matter of preference. Personally I like to have it at the top, so that as soon as you open the code you can see exactly what its doing and then go to the definitions of the methods from there. I think it makes more sense then opening a file and seeing a bunch of random methods and then scrolling to the bottom to see them actually being called.

As I said, its all preference though. Either:

function myMain(){
  methodOne();
  methodTwo();
  methodThree();
}

function methodOne(){
  //code here
}
function methodTwo(){
  //code here
}
function methodThree(){
  //code here
}

Or:

function methodOne(){
  //code here
}
function methodTwo(){
  //code here
}
function methodThree(){
  //code here
}

function myMain(){
  methodOne();
  methodTwo();
  methodThree();
}
晒暮凉 2024-10-01 15:15:03

当语言同等地允许其中之一时(即:不需要前向声明),我更喜欢将主代码放在顶部。对我来说,它可以作为代码功能的概述,因此让人们在查看源文件时首先看到的东西似乎是合理的。

不过,我相当不喜欢前向声明(它们闻起来像重复),而且它们必须出现在主代码之前,这违背了将 main 放在第一位的整个目的)。因此,在 C 或 C++ 中,我通常会将 main 放在底部(大多数 C/C++ 程序员都希望它位于底部)。

When the language allows either one equally (ie: no forward declarations required), i prefer to have the main code up top. To me it serves as an overview of what the code does, so it seems reasonable to have that be the first thing someone sees when they view your source file.

I rather dislike forward declarations, though (they smell like duplication), and they'd have to come before the main code, which defeats the whole purpose of having main be first). So in C or C++ i'll generally have main at the bottom (where most C/C++ programmers would expect it to be anyway).

凶凌 2024-10-01 15:15:03

我认为最好将主要逻辑放在顶部。如果其他人阅读代码,他可能会从文件的顶部开始。将主要逻辑放在该位置将使他能够大致了解该文件中的代码应该执行的操作。主逻辑中的函数调用还告诉他在哪里深入研究逻辑。

In my opinion it's better to put the main logic at the top. If someone else reads the code he will probably start at the top of the file. Having the main logic at that place will give him already an overview what the code in this file is supposed to do. The function calls in the main logic also tell him where to dive deeper into the logic.

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