英文:
Is it a good practice to have an interface which has default implementation for all of its methods?
问题
假设我有一个如下所示的接口:
public interface DataChecker<T, C> {
default ProcessResult beforeProcess(T record, CountertHelper countertHelper, C config){
return new ProcessResult(false, Collections.emptyList());
}
default List<String> checkData(T record, CountertHelper countertHelper, C config) {
return Collections.emptyList();
}
@RequiredArgsConstructor
@Getter
class ProcessResult {
private final boolean skip;
private final List<String> keys;
public ProcessResult(boolean skip) {
this.skip = skip;
this.keys = Collections.emptyList();
}
}
}
这个接口的一些实现者可能只实现beforeProcess
方法,而其他一些可能只实现checkData
方法,还有一些可能选择同时实现这两个方法。
将它们都设为default
方法,这样做是否是一种良好的实践呢?或者更一般地说,一个接口是否最好为其所有方法提供default
实现呢?
英文:
Imagine I have an interface like below:
public interface DataChecker<T, C> {
default ProcessResult beforeProcess(T record, CountertHelper countertHelper, C config){
return new ProcessResult(false, Collections.emptyList());
}
default List<String> checkData(T record, CountertHelper countertHelper, C config) {
return Collections.emptyList();
}
@RequiredArgsConstructor
@Getter
class ProcessResult {
private final boolean skip;
private final List<String> keys;
public ProcessResult(boolean skip) {
this.skip = skip;
this.keys = Collections.emptyList();
}
}
}
Some implementer of this interface may only implement beforProcess
method and some others may only implement checkData
method and some others may chose to implement both of them.
Is it a good practice to make both of them default
? Or more generally is it a good practice to have an interface which has default
implementation for all of its method.
答案1
得分: 1
如其名,Java 8 中的 default 方法只是默认的。如果您不进行覆盖,调用类将会调用这些方法。
在您的情况下,如果 Some 类只想要 beforProcess
而不想要 checkData
,反之亦然,我建议您将接口拆分为两个部分,如下所示:
public interface DataChecker<T, C> {
List<String> checkData(T record, CountertHelper countertHelper, C config);
}
以及
public interface DataProcessor<T, C> {
ProcessResult beforeProcess(T record, CountertHelper countertHelper, C config);
}
现在这种方法更清晰,类可以根据需要覆盖一个或两个方法,从而实现更清晰的方法。
英文:
As name implies, default methods in java 8 are simply default. If you do not override them, they are the methods which will be invoked by caller classes.
In you case if the Some class only want beforProcess
and do not want checkData
and vice versa I suggest you to split ur interface into 2
like
public interface DataChecker<T, C> {
List<String> checkData(T record, CountertHelper countertHelper, C config);
and
public interface DataProcessor<T, C> {
ProcessResult beforeProcess(T record, CountertHelper countertHelper, C config);
Now the approach is cleaner and the classes override one or both if implemented both hence a cleaner approach.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论