Question

I really wonder that put an Interface and a (Implemented) class in same package or separate is better. I usually put them in same package since I believe it is more convenient to compare.

But couple of days ago, I had an opportunity to use apache GenericObjectPool. Then I found such a package structure like org.apache.commons.pool.impl.

After all, my question is when should I use former one and when should I use the other. Thanks for your sincere answers in advanced:D

Was it helpful?

Solution 2

If use interfaces just to lower the coupling, you can put interface and implementation into the same package. If you primarily count with more implementations if the interfaces, you should put them in separate package. This really depends on your design and I don't think there is a strict rule. Generally you should design you application as simple as possible and do the refactoring later. So when you start, you can put the implementation into the same package and only when it seems to be needed, you should split it.

OTHER TIPS

One of the tenets of composition is that interfaces are separated from their implementation.

Therefore it doesn't make much sense to constrain interfaces and their implementations to the same package.

(On a system I work on the interfaces are placed in a common area - loosely based on a concept of an interface repository).

If you define the responsibility of a package by its interfaces and classes, you attempt to abstract from concrete implementations. Hence, your package should consist of public types only.

If you continue to provide a default implementation for your package, I do not see any reason why not to put them into the same package. But I would always suggest to put your implementation into a separate project or more specific, to provide the API of your package and the implementation as two different artifacts (for example, jar-files).

Doing things this way, you support the following important aspects of abstraction:

  • replacement of one implementation with another
  • ensuring that client code depends only one the API and not the implementation (by adding only the API artifact to the clients classpath)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top