Below is a Java class constructor which accepts a callback for error handling. null
should be an acceptable value, and if the passed value is null
then skip error handling.
I have two ways of checking if the callback passed is able to be accepted, and my question here is which method (if either) would be the best for long-term maintainability and sanity. I am open to suggestions as well if anyone believes that there are better ways of going about this, as I am relatively new to using Java.
class ErrorMaker {
public ErrorMaker(Consumer<Throwable> onError) {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
try (InputStream inputStream = classloader.getResourceAsStream("\\\\..\\..")) {
Properties config = new Properties();
config.load(inputStream);
// ...
} catch (Exception err) {
// METHOD #1 - null comparison
if (onError != null) {
onError.accept(err);
}
// METHOD #2 - instanceof
if (onError instanceof Consumer<?>) {
onError.accept(err);
}
}
}
}
Thanks in advance.
instanceof
it's initally not meant to be used for your usecase. To make things clear for other coders in terms of readability and logic you should either go woth classiconError != null
or alternativelyObjects.nonNull(onError)
. But if you have to check whether your error is an instance of a specific class then of course instanceof is ok, but you ask for null checking, therefore don't try to trick coders thinking in one way when actual you mean something else.instanceof
can be confusing, it is hiding the real purpose - if you want to check fornull
, just do!= null
(or similar)