Java API Design – Is Implementing an Interface in a Subpackage an Anti-Pattern?

anti-patternsapi-designjavapatterns-and-practices

Let's say I have the following:

package me.my.pkg;
public interface Something {
    /* ... couple of methods go here ... */
}

and:

package me.my;
import me.my.pkg.Something;
public class SomeClass implements Something {
    /* ... implementation of Something goes here ... */
    /* ... some more method implementations go here too ... */
}

That is, the class implementing an interface lives closer to the package hierarchy root than does the interface it implements but they both belong in the same package hierarchy.

The reason for this in the particular case I have in mind is that there is a previously-existing package that groups functionality which the Something interface logically belongs to, and the logical (as in both "the one you'd expect" and "the one where it needs to go given the current architecture") implementation class exists previously and lives one level "up" from the logical placement of the interface. The implementing class does not logically belong anywhere under me.my.pkg.

In my particular case, the class in question implements several interfaces, but that feels like it doesn't make any (or at least no significant) difference here.

I can't decide if this is an acceptable pattern or not. Is it or is it not, and why?

Best Answer

Yes, it's acceptable, as long as the class and the interface are both definitely in the correct packages.

Organising classes into a hierarchical set of packages is a bit like organising classes into an inheritance hierarchy. It works pretty well most of the time, but there are plenty of legitimate cases which just don't fit.

Note that Java doesn't really even have a package hierarchy - the hierarchical nature doesn't extend further than the folder structure. I can't speak for the Java language designers, but I doubt they made this decision by accident!

I sometimes find it helps to think of the 'package hierarchy' as an aide to help programmers find the package they're looking for.