I am creating interface in Java for custom error handler.
Want to pass an argument error object but I need it to be child of Exception
class.
Is it okay to use my defined class name in an interface ?
Won’t it make it less of an interface in terms of not being dependent
on any implementation ?
I try to do something like this:
public class CustomException {
/* ... Implementation ... */
}
public interface Interface {
void onError(CustomException ex);
}
10
First I have to point out the fact that CustomException
doesn’t extend Exception
so it is not really an Exception
.
That said:
If you don’t care about Dependency Inversion Principle, then leave it as it is. It’s perfectly OK for an interface to depend on concrete classes, for example many interfaces depend on String
or Object
which are concrete classes. The thing is that we would tend to believe that classes that belong to the Java SDK are more stable (less prone to code-breaking changes) than the ones we write.
In the other hand:
If you want to follow the DIP (which has countless benefits and is my recommendation), then you have to do one of two things:
Option 1
- Make
CustomException
abstract - Keep
void onError(CustomException ex)
as it is
Option 2
- Make
CustomException
an interface - Keep
void onError(CustomException ex)
as it is
With either of those options you would be conforming to the DIP, since the interface would not depend on any concrete class, only on abstractions.
In a direct application of dependency inversion, the abstracts are
owned by the upper/policy layers. This architecture groups the
higher/policy components and the abstracts that define lower services
together in the same package. The lower-level layers are created by
inheritance/implementation of these abstract classes or interfaces.
Martin, Robert C. (2003).
- Agile Software Development, Principles, > Patterns, and Practices. Prentice Hall. pp. 127–131. ISBN
978-0135974445.
9
Tulains is right – interfaces depend on concrete classes all the time. They are only meant to create a contract for their own concerns. That contract can involve taking and returning any kind of data.
Remember that in higher level languages, even primitive types are not so primitive. So you’re working with concrete types anyway!
I suppose by name, you mean the actual class itself. If you are trying to specify the actual exception class name in order to initialize the corresponding exception through Reflection, this is not the right way to go.
If you want to use a custom class in an interface, you can, of course, use your own classes in your own interfaces. The classes become parts of the public interface of your library/API. Data structures and exceptions are a good example of the classes which are often used by the interfaces.
If you need to use different exceptions depending on the context, then you may be interested in using generics.
3