且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

main()方法在Java类文件中的优选位置

更新时间:2023-11-18 15:49:52

这些只是我的想法:



main()是一个与对象实例无关的静态方法。我们知道它存在作为一个入口点,这使我们的程序/类可执行。



事情是在Java中,一切(但primitives)是一个对象, main()必须在某个类中声明。这样的静态方法可以执行的代码更关心设置程序执行,并委托我们的业务逻辑(实际上做某事的对象)来运行应用程序。因此,它的关注与我们的类的其余部分(它定义了一些我们试图封装的数据和行为)不同。



main()属于我们日常类的数据和行为,因为我怀疑每个类都需要自己执行。 main()的关注点是运行我们的程序。因此,它应该在与应用程序启动/执行相关的项目的模块中声明为远离我们的业务对象。所以,正如你可能猜到的,我提出了你所说的不建议 - 尽量远离你的类和逻辑,并且只在你的应用程序的入口点的上下文中声明。 / p>

对于文件本身中的位置,我并不认为它很重要 - 只要显而易见的是,该文件中的代码涉及设置和运行程序。


When it comes to order/sequence methods in java class. Where do you expect/prefer to see main() method?

  • at the top before each field (to stress user its existence and force him to use it )
  • at the bottom (to let user see fields first and after that discover main)
  • after c-tor
    or ... .

Please share your thoughts, this is kind of stylistic/philosophical question. Please do not suggest to keep main() in separate file alone.

These are just my thoughts:

main() is a static method unrelated to object instances. We know that it exists as an entry point, that makes our program/class executable.

The thing is that in Java, everything (but primitives) is an object, so main() must be declared in some class somewhere. The code such a static method may execute is more concerned with setting up the program for execution, and delegating to our business logic (objects that actually do something) to run the application. As such, its concern is distinct from the rest of our class (which defines some data and behaviour that we are trying to encapsulate).

main() doesn't really belong with the data and behaviour of our everyday classes, as I doubt that every class needs to be executable on its own. main()'s concern is with running our program. As such, it should be declared away from our business objects, in a module of the project concerned with application launch/execution. So, as you might be guessing, I am proposing exactly what you've said not to suggest - keep main away from your classes and logic as much as possible, and only declare it in the context of an entry point to your application.

As to the location within a file itself, I don't really think it matters - as long as it is obvious that the code in that file is concerned with setting up and running the program.