Java Package Policy

I always doubt when creating packages, I want to use limited access to the package, but at the same time I want similar classes to be divided into packages. The problem arises when you realize that packages are not hierarchical in Java:

At first the packages seem hierarchical, but they are not. a source

Imagine that I have an API defined with its classes on foo.bar, only the classes that the API client needs are made public. Then I have another package with some internal objects that I need in the API defined in foo.bar.pojos, these classes must be public, so they can be accessed through foo.bar, but that means the client API also can access them if the package foo.bar.pojos is imported.

What is the general package policy that should be followed?

+6
source share
3 answers

I saw two ways to do it.

The first is to separate the open API and inner classes from two different artifacts (jars). The documentation is also divided, and therefore it is easy for end users to distinguish between what is internal and what is not. But sometimes it is more difficult to have two banks, two source trees, etc.

The second is to supply a single can, but there is good documentation to find out what is internal and what is not. Textual documentation can explain how to use the API (and thus avoid talking about internal components). And javadoc can indicate that the class is intended for internal use and, therefore, can be changed.

+4
source

Yes, Java packages do not give you enough control over your dependencies. The classic way to handle this is to put external APIs in one package and internal implementation classes in another, and rely on people with a good feeling to avoid creating dependencies on the latter.

With Maven and OSGI, you have an additional mechanism for managing dependencies between modules / package packages. In the case of OSGI, you can explicitly declare some packages as not exported, and the OSGI-oriented development environment will prevent people from creating harmful dependencies. Maven module support is weaker, but at least it controls dependency cycles.

Finally, you can use the PMD custom rules to enforce the modular design conventions of the project ... in the same way that there are rules that prevent Java dependencies on the "com.sun. *" Package tree.

+2
source

This is a mess.

Using only what Java offers, you must put everything in the same package. You get a single (or several) package with a large number of classes and you cannot easily group them for yourself (but at least this problem does not arise from the outside). However, most people do not, and as a result, your (as a developer on top of these libraries) public path to the classes is filled with materials that you never need to see.

You might like OSGi, which (and provides) the concept of package packages. They are not exported to the outside world.

+1
source

Source: https://habr.com/ru/post/891708/


All Articles