【发布时间】:2018-01-04 09:26:02
【问题描述】:
我有两个用 JAVA 实现的阅读器。见下文:
public final class ReaderA {
public ReaderA() {}
public static int read(final File file) {
final byte[] data = Files.readAllbytes(file.toPath());
return read(data);
}
public static int read(final byte[] data) {
// do somethingA
}
...// and some other methods
}
public final class ReaderB {
public ReaderB() {}
// this method is exactly the same as in ReaderA
public static int read(final File file) {
final byte[] data = Files.readAllbytes(file.toPath());
return read(data);
}
// this is implemented different from the one in ReaderA
public static int read(final byte[] data) {
// do somethingB
}
...// and the same other methods as in ReaderA
}
问题。避免重复代码的最佳方法是什么?
我尝试在新的抽象类Reader 中提取重复代码,并尝试将read(final byte[] data) 抽象化并在子类ReaderA 和ReaderB 中实现它。它不会起作用,因为方法是静态的。
【问题讨论】:
-
如何将其抽象化?
-
你为什么要把
read(final byte[] date)方法抽象化?我认为你想提取重复的代码,所以这个方法不能是抽象的,因为你有(常见的)实现! -
删除静态,但我不会这样做,因为调用方法
read(File)的整个代码会有很多变化。 -
read(final byte[] data)在两个类中都不相同@NiklasP -
为什么这些方法需要是静态的?
标签: java code-duplication