When I first started programming, I wrote everything in main. But as I learned, I tried to do as little as possible in my main()
methods.
But where do you decide to give the other Class/Method the responsibility to take over the program from main()
? How do you do it?
I've seen many ways of doing it, like this:
class Main
{
public static void main(String[] args)
{
new Main();
}
}
and some like:
class Main {
public static void main(String[] args) {
GetOpt.parse(args);
// Decide what to do based on the arguments passed
Database.initialize();
MyAwesomeLogicManager.initialize();
// And main waits for all others to end or shutdown signal to kill all threads.
}
}
What should and should not be done in main()
? Or are there no silver bullets?
Thanks for the time!
Code in the main function:
Therefore code in the main function:
In practice, this means that real apps don't have much in main. Toy apps and one-shot programs might have quite a lot in main, because you aren't planning to test or reuse them anyway.
Actually, some of what I say above is C++-specific. Java main methods of course can be called by test code or variant apps. But they still don't take objects as parameters, only command-line arguments, so the extent to which they can be isolated under test, or behave well in terms of re-use, is quite low. I guess you could pass class names for them to instantiate and use to create the rest of the app.
[Edit: someone has removed the "C++, Java" tags from this question. So: what I say above is C++ and Java specific. Other languages may treat main in a way which is less special, in which case there may be no particular reason for you to treat it specially either.]
In my opinion, the "main" of a sizable project should contain around 3 function calls:
Any sizable application will be divided into chunks of functionality, usually with some hierarchy. The main controller may have several child controllers for specific features.
Doing it this way makes it much easier to locate specific functionality, and separation-of-concerns is better.
Of course, as other replies have said, there really is no silver bullet in software development. For a short project I might put everything in main just to get things up-and-running quickly. I think also depends on the language - some options may be easier than others in particular languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With