Java - 在主类中放入多少逻辑? [英] Java - how much logic to put in the main class?

查看:104
本文介绍了Java - 在主类中放入多少逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你通常在主类中加入多少逻辑?主类中的逻辑应该是最小的,只是实例化其他专用类,并从那里运行所有任务吗?

How much logic do you normally put in the main class? Should logic in the main class be at minimum, only instantiating other, specialized classes, and running all the tasks from there?

如果您对此主题有任何建议(或外部文章),我很感激。

If you have any suggestions on this topic (or external articles), I'd appreciate it.

推荐答案


主类中的逻辑是否应该在最小,只实例化其他专业类,并从那里运行所有任务?

Should logic in the main class be at minimum, only instantiating other, specialized classes, and running all the tasks from there?

是的。理想情况下, main 方法及其周围类只能用作启动程序的入口点。仅仅存在周围的类只是Java程序组成方式的一个工件(所有必须在某个类中),并且除了<$之外没有理由为什么它应该包含其他东西c $ c> main 方法(但肯定有理由不这样做)。

Yes. main method and its surrounding class should ideally be used only as an entry point to start the program. The mere existence of the surrounding class is just an artifact of the way Java programs are composed (everything must be inside some class), and there's no reason why it should contain other stuff in addition to the main method (but there definitely are reasons why it shouldn't).

当你得到有趣的类(那些形成实际的程序)分开,你打开各种灵活性的大门。也许其中一些类可以用在其他一些项目中。也许有一天你会想要用更好的实现来替换它们中的一些。也许你会找到一个更好的命令来实例化所有这些类 - 所以只需交换几行。或者如何在并行线程中执行冗长的启动加载和实例化?只需将其中的一些包装到合适的Executors中。祝你好运,尝试使用1000多行主类。

When you get the interesting classes (those that form the actual program) separated, you open doors for all kinds of flexibility. Perhaps some of those classes could be used in some other projects. Perhaps some day you'll want to replace some of them with better implementations. Maybe you'll find a better order to instantiate all those classes - so just swap a few lines. Or how about executing lengthy startup loadings and instantiations in parallel threads? Just wrap some of them to suitable Executors. Good luck trying this with a 1000+ line main class.

这种灵活性对于除了100行基本示例,原型等之外的所有内容都很重要。但考虑到即使是小工具也会增长,为什么不从一开始就正确地做到这一点?

This kind of flexibility matters for everything except maybe for 100-line elementary examples, prototypes and such. But given that even small tools tend to grow, why not do it correctly right from the beginning?

这篇关于Java - 在主类中放入多少逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆