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开发者_如何学C 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 [;-)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".
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.
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.
Its not bad thing but It is certainly good practice to separate interface and implementation in different packages.
for example
com.mycompany.domain.service
com.mycompany.domain.service.impl
Advantages:
- Uniform package structure
- Some time when you want to process some classes only, you can differentiate it by package
精彩评论