Search code examples
javacode-organization

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
[;-)


Solution

  • 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.