Search code examples
language-agnosticmain-method

In languages where you have a choice, is it better to put the main function/method/code at the top or bottom?


When 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?


Solution

  • 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();
    }