In languages where you have a choice, is it better to put the main function/method/code at the top or bottom? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this questionWhen you're writing a program that consists of a small bit of main logic that calls a bunch of supporting functions, you can choose either put the main logic at the top of the file or the bottom (Let's assume the language allows either.) Which is better? Should I put my main logic at the beginning of the file or the end, after all the supporting functions? Is there a significant difference in utility/readability/understandability between the two?
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();
}
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).
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.
精彩评论