java 如何组织类、包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7515503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:18:35  来源:igfitidea点击:

How to organise classes, packages

javapackages

提问by blue-sky

How do you decide what a package name should be and what class should go into what package ?

你如何决定包名应该是什么以及哪个类应该放在哪个包中?

I'm working on a project where I am constantly adding/removing classes and not really sure if I need a new package, or should add it to an existing one that im not currently aware of.

我正在开发一个项目,在该项目中我不断添加/删除类,但不确定是否需要新包,或者是否应该将其添加到我目前不知道的现有包中。

Do you follow a set of rules when creating a new package ?

创建新包时您是否遵循一组规则?

How do you know if you are not duplicating package functionality ? Is this just down to familiarity with the project.

你怎么知道你没有复制包的功能?这是否仅仅取决于对项目的熟悉程度。

Any pointers appreciated.

任何指针表示赞赏。

回答by michael667

I strongly discourage from organizing packages from an implementational point of view, like controllers, data, etc. I prefer grouping them by functionality, that is, feature1, feature2, etc. If a feature is reasonably complex and requires a large number of classes, then (and only then) I create subpackages like above, that is, feature1.controllers, feature1.data, etc.

我从来看,像一个实施过程中的点组织包极力劝阻controllersdata等我更喜欢按功能将它们分组,那就是feature1feature2等等。如果某个功能是相当复杂的,需要大量的类,那么(只有然后)我创建如上子包,也就是feature1.controllersfeature1.data

回答by Josh Pordon

Classes should do one thing (Single Responsibility Principle).

类应该做一件事(单一职责原则)。

Classes that do related things should go in the same package. If you find you can more closely relate some of the classes in a package, make them a subpackage!

做相关事情的类应该放在同一个包中。如果您发现可以更紧密地关联包中的某些类,请将它们设为子包!

For example, if I had a project with these classes:

例如,如果我有一个包含这些类的项目:

  • GreetingInputWindow
  • GreetingDatabaseObject
  • GreetingDatabaseConnector
  • GreetingInputWindow
  • GreetingDatabaseObject
  • GreetingDatabaseConnector

I might just put them all in the greetingpackage. If I wanted to, I might put GreetingInputWindowin the greeting.uipackage, and the other 2 into the greeting.dbpackage.

我可能只是把它们都放在greeting包里。如果我想,我可能把GreetingInputWindowgreeting.ui包装,另2成greeting.db包。

回答by Ger

I don't believe there are any hard and fast rules on packaging convention (though I could be wrong). Normally I break it up into

我不相信包装约定有任何硬性规定(尽管我可能是错的)。通常我把它分解成

com.mycompanyname and then:

com.mycompanyname 然后:

  • api
  • controllers
  • data (for models)
  • jobs (for cron jobs)
  • reporting
  • servlet
  • utils
  • 接口
  • 控制器
  • 数据(用于模型)
  • 工作(用于 cron 工作)
  • 报告
  • 小服务程序
  • 实用程序

If I find I have a class which does not fit into any of those, then I create a new package.

如果我发现我有一个不适合其中任何一个的类,那么我会创建一个新包。