During refactoring, I needed to extend existing interface by adding the extra parameter. Now there are many old classes that implement version without parameter, and some new classes that implement the version with parameter:
void exec(int parameter);
vs
void exec();
Ultimately, I need to accept classes implementing both interfaces into the same collection and later process inside the same method. It seems there are two possible approaches for that:
\1. Use instanceof
:
int parameter = ...
if (a instanceof NewInterface)
((NewInterface) a).exec(parameter);
else
((OldInterface) a).exec();
The benefits of this is that NewInterface
and OldInterface
can be independent interfaces. When the developer writes a new class, it may be more obvious which methods to override, and overriding the wrong method will result a compile time error.
\2. Use single interface with both methods defined and the parent abstract class that redirects from one method to another:
abstract class Common {
abstract void exec();
void exec(int param) { exec(); }
}
This allows to avoid instanceof
that is considered bad in some discussions, but now in every new class we must add a weird looking stub:
// This is not used anymore
void exec() { };
// This is a real functionality
void exec(int param) { ...
Does not look like the best design ever either, especially taking into consideration the possibility to call this stub by error.
Should I use some third approach, or is this the case when the usage of the instanceof is reasonable?