0

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?

Rhexis
  • 2,414
  • 4
  • 28
  • 40
  • 4
    There is no "BEST" way. For anything, ever. In fact in this case I don't even think the goal is actually worthty at all. – Jan Hudec Aug 24 '11 at 07:30
  • 2
    This is too vague to answer in it's current form, and most likely produce a bunch of opinions. Do what you think makes sense to the guy who will maintain the code after you... – Nim Aug 24 '11 at 07:31

2 Answers2

9

Avoid globals/singletons like swine-flu, its a bad practice and can have really bad effects on larger multi-threaded projects. Seeing as you are using C++, you can wrap your app into one big manager type class that has everything nicely factored into a style that suites you/your coding style, then in main all you need to do is:

int main(int argc, char** argv)
{
    Application MyApp(argc,argv);
    return MyApp.start();
}

which is pretty uncluttered

Necrolis
  • 25,836
  • 3
  • 63
  • 101
2

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 Config class that you initialize from argc and argv and/or possibly a file, and then use that as storage for the user controllable parameters.

Another common pattern is moving all of main into a class, that contains the state as member attributes and has a run (or main call it as you wish) member function. This allows for an easy refactor of main where 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 of main.

There is no clear answer, as it depends on what your main is 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...

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489