如何清理杂乱的 main()?
为了使 main() (在 C++ 中)尽可能干净/小,您可以选择一些选项,但其中哪一个最好?初始化 main 中的所有变量,在 main 之外将它们初始化为全局变量,在 .h 中将它们初始化为全局变量,在 main 中初始化它们,但在其他地方设置它们的值(通过将它们传递给函数)。可能还有其他方法,但是,保持 main() 尽可能干净/清晰/小的最佳方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
避免像猪流感这样的全局/单例,这是一种不好的做法,并且会对大型多线程项目产生非常糟糕的影响。鉴于您正在使用 C++,您可以将您的应用程序包装到一个大型管理器类型类中,该类将所有内容都很好地分解为适合您/您的编码风格的样式,然后主要您需要做的就是:
这非常整洁
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:
which is pretty uncluttered
有一些常见的模式,例如将数据和操作封装在有意义的类中。例如,如果您处理命令行参数或文件中的配置,则可以创建一个从
argc
和argv
初始化的Config
类和/或者可能是一个文件,然后将其用作用户可控参数的存储。另一种常见模式是将所有
main
移至一个类中,该类包含作为成员属性的状态,并具有run
(或main
将其称为你希望)会员功能。这允许轻松重构main
,您不必将所有状态作为函数参数传递。有时这两个选项会混合在一起,类会从main
的参数进行初始化。没有明确的答案,因为这取决于您的
main
当前正在做什么,在某些情况下,如果不同的部分不同,那么保留一个长 main 仍然是有意义的明显分开,并且不是太长,其中long-ish和long是主观测量......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 fromargc
andargv
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 arun
(ormain
call it as you wish) member function. This allows for an easy refactor ofmain
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 ofmain
.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...