I have two readers implemented in JAVA. See below:
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
}
Question. What's the best way to avoid the duplicate code ?
I tried to extract a the duplicated code in a new abstract class Reader
and tried to make the read(final byte[] data)
abstract and implement it in subclasses ReaderA
and ReaderB
. It will not work because the methods are static.