开发者

Java package structure

As a best-practice, is it ok for interfaces / classes in higher level packages to depend on interfaces / classes in lower level packages?

e.g.

can com.company.core.SomeClass depend on com.company.core.apackage.AnotherClass

Or should the dependencies flow the other way? I am trying to eliminate cycles between packages开发者_JAVA技巧.


Typically, a user of a package might be interested in com.company.functionality.MainUse, which is implemented using com.company.functionality.implementationdetail.FiddleWithStuff, so I'd say you have to accept dependencies in that direction.

But the other direction is probably necessary as well, as implementation detail classes may need to implement interfaces that is part of the interface to the functionality.

So, unfortunatley, I think a strict directionality like that isn't a workable way to avoid cycles.


They usually flow the other way. com.mycompany.myproduct.Widget is an interface, and com.mycompany.myproduct.fancy.Button implements it.

There are however big exceptions to this general rule, and there is no reasons why it should be a rule.

Packages themselves are simply folders, except for primitive access rules on methods and fields.

What is far more important are dependencies between bundles, that is (in their basic form) jars. Having jar A depend on jar B depending on jar C depending again on jar A is a real problem. If you have the same circle between packages in the same jar, it can cause frustration in people who read or debug your code, or in elitists reading it, but is not a big issue.


Such dependencies are common even in the Java API itself.

Look at: http://download.oracle.com/javase/6/docs/api/java/awt/image/renderable/package-use.html

You can see that classes in java.awt use classes in java.awt.image.renderable.

(ADDENDUM) Bottom line: Both directions are used in practice. One is not, IMHO, necessarily better than the other.


Sure, you're using the so-called top-down approach, a package depends on its subpackages but not vice versa.

The bottom-up approach would be the other way around, a package would depend on its parent packages but not vice versa.

Either way is fine as long as you are able to maintain consistency, but the top-down approach is easier and more common.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜