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
[;-)
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.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With