I’m in doubts this design is OK, it may be there is a way to do it better? The case is that I need a class which would be used in one and only class and that’s it. But, this class needs to inherit from another one, which is in another package. This doesn’t sound right as for me.
public class User {
private class SpecificParser extends BaseParser {} // BaseParser.java is in another package
}
I would simply create SpecificParser
as a separate class, but don’t want to do that also because the only consumer of it is a User
class.
There are two issues at hand. The first being “Is extending a class from another package in a different package bad design” the second dealing with dependencies.
Short version, its fine.
There is nothing fundamentally wrong about extending a class from a different package in another package. Indeed, sometimes this is the only way to do it. One cannot extend the HashMap
class and place the resulting class in java.util
.
Consider the classes in java.lang
that get extended into other classes all over the place – Object
, Number
, Thread
.
In many casses from third party frameworks, one will have a sealed jar which prevents one from putting a class into that namespace, yet is intended to be extended in other code.
There is nothing wrong with extending a class from some other package. That the class is a private inner class makes this even less of an issue (as it is hiding the implementation details within itself).
Dependencies are a nightmare – and one that we have to live with. There are two parts to this. There is the ‘you have created a dependency from User
to BaseParser
‘. Given the name of BaseParser
, it is fairly clear that it is intended to be extended. You just have to make sure that you document that dependency and have the appropriate tests to make sure it works the way you want it to.
There will be a dependency one way or the other. It is probably better to have something depending on a BaseSomething
than for some random class in another package depending on some specific other class.
You also want to avoid a circular dependency. It isn’t too much of an issue in terms of “never do this because it will break things” but rather “avoid doing this because it creates situations where you will make a change in A that will break something in B, and fixing B will break something else in A. There is much written on this subject. Two examples from Stack Overflow:
- Dealing with a Circular Dependency
- How to remove circular dependency from two classes which are concrete types
2
I don’t think the fact that SpecificParser
is a nested class is a problem in itself. What you should think about is whether it is ok in general to have a dependency on the package containing BaseParser
. For example, if this would result in a circular dependency between the two packages, that would be bad. From the looks of it, in this case it should not be a problem, since it is unlikely that a parser would ever depend on a user. 🙂
2