In order to keep the main() (in c++) as clean/small as possible, there a a few options you can choose but which of them is best? initialize all variables in main, init them outside of main as global, global in .h, init them in main BUT set there values elsewhere (by passing them over to a function). there may be other ways but, what is the BEST way to keep the main() as clean/clear/small as possible?
Share
There are some common patterns, like encapsulating data and operations in classes that make sense. For example, if you process command line arguments or configuration from files, you can create a
Configclass that you initialize fromargcandargvand/or possibly a file, and then use that as storage for the user controllable parameters.Another common pattern is moving all of
maininto a class, that contains the state as member attributes and has arun(ormaincall it as you wish) member function. This allows for an easy refactor ofmainwhere you do not have to pass all of the state as function arguments. Sometimes those two options are mixed and the class initializes from the arguments ofmain.There is no clear answer, as it depends on what your
mainis currently doing, in some cases it still can make sense to keep a long-ish main if the different parts are clearly separated and it is not too long, where long-ish and long are subjective measures…