Java主要方法,良好的编码风格 [英] Java Main Method, Good Coding Style

查看:281
本文介绍了Java主要方法,良好的编码风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经和我的一个朋友进行了很长时间的讨论,关于Java中main方法的正确和良好使用。基本上我们有这样的类:

I've had quite a long discussion with a friend of mine about the correct and good use of the main method in Java. Basically we have a class like this:

public class AnImporter implements Runnable {
  // some methods, attributes, etc.
}

但是在哪里放置main方法?我认为一个好的做法是保持代码在它所属的,从而把上面的代码转换为

But where to put the main method? I concider it a good practice to "keep code where it belongs", thus turning the above code into

public class AnImporter implements Runnable {
  public static void main(String [] args){
    // Startup code for Importer App here
  }
  // some methods, attributes, etc.
}

虽然我的伙伴认为启动代码与应用程序本身无关它应该放在另一个类,像这样:

While my buddy argues that "the startup code has nothing to do with the application itself", thus it should be placed in another class, like this:

public class AnImporter implements Runnable {
  // some methods, attributes, etc.
}

public class AnApplication {
  // Nothing here
  public static void main(String [] args){
    AnImporter a = new AnImporter();
    // Startup code here
  }
  // Nothing here
}


b $ b

尽管我们在一段时间内讨论了这个问题,但是我们并没有得出结论,在Java中哪种方式是更好的方法。你对这个话题的反对是什么?

Despite the fact that we discussed the matter for some time we both ended up with no conclusion on which way is the better approach in Java. What's your oppinion on this topic? Where and most importantly, why, do you place your main method where you placed it?

推荐答案

我同意你的朋友的意见。您正在AnImporter中构建一个可能可重用的服务,可能可以在多个程序中使用多个主要。所以,使一个主要的特殊和嵌入它在AnImporter没有什么意义。

I agree with your friend. You're building up a potentially reusable service in AnImporter that could potentially be used in multiple programs with multiple main's. So, making one main special and embedding it in AnImporter doesn't make much sense.

这篇关于Java主要方法,良好的编码风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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