import java.util.List;
public interface IEntityParam {
public void validateParam(Object object);
public default void validateParam(Object object,List<String> Str){
validateParam(object);
}
}
Suppose IEntityParam
is very old interface extended by many classes and I need new method in it. I have added a new method in with another parameter.
But my default implementation doesn't use new parameter List in its default method. Technically, there is no problem. But is it correct use of default method? Or Should I keep this new method to specific class as I am not using second parameter in default implementation.
Note : The list of String which is supplied here is used in just one implementation right now but can be used in other implementation in future. It is not very specific and can be used by other implementation as well.
This is probably a misuse of default methods. Default methods are known to facilitate backward compatibility when interfaces/contracts evolve with new methods, but the problem in your case is that not all IEntityParam
implementations care about the new version of the "contract". Default methods are conceptually part of the interface's contract.
The normal way to address your current need is to extend the interface:
public interface IEntityParam {
public void validateParam(Object object);
}
public interface IEntityParamExtended extends IEntityParam {
public default void validateParam(Object object,List<String> Str);
}
This way, your class that needs the second method will implement IEntityParamExtended
and provide an implementation for both methods; while all other implemnetations of IEntityParam
remain unaffected.
In the future, when IEntityParamExtended
needs to be promoted to IEntityParam
(i.e., when the new method forms part of the IEntityParam
contract), you can use a default
method to avoid forcing all existing implementations to be changed and recompiled.