Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to 'mix class and interfaces in the same package'?

I just found something that I never heard of before and I do not agree with (by now). In an (upvoted and not further commented) answer I read "why to mix class and interfaces in the same package"

So I wonder, if there are reasons to separate Interfaces and implementations in Java.

I know that we are not obliged to have all implementations in the package of the interface, but is it (sometimes) wise to have none there?

Regards
Mike
[;-)

like image 637
DerMike Avatar asked Jan 05 '11 10:01

DerMike


3 Answers

Reasons for keeping interfaces and implementation in separate packages:

clear code base - It 'looks' better, tidier if we have one package with interfaces and another one with implementations (usually a something.impl namespace). And the code structure shows/reflects that you code against interfaces.

access modifiers - We can use package private access modifiers for some package private API for related interface implementations.

library structure - Maybe one day you decide to create different libraries for API (interfaces) and implementation(s). Then it's pretty good to have interfaces and implementations in different packages. So you can change the build without refactoring your code base.

like image 25
Andreas Dolk Avatar answered Oct 24 '22 18:10

Andreas Dolk


I agree with org.life.java - I will have service and underlying service.impl packages, but always in that kind of an arrangement.

I disagree with the wording "bad practice". That's too strong.

The java.util Collections API conflicts with this advice. I would not want to be the one to tell Joshua Bloch that he had done a "bad job".

like image 63
duffymo Avatar answered Oct 24 '22 18:10

duffymo


For OSGi it's almost required to use separate packages AFAIK so you can export/import the API without exporting/importing the implementation.

For interfaces that are only internally however it's not a problem to keep everything in one package.

like image 33
Thomas Mueller Avatar answered Oct 24 '22 17:10

Thomas Mueller