I'm not saying you should use an interface is your particular case, but I'll try to cover some of the points you might want to consider.
So, a couple of questions to ask yourself to begin with:
- Are there common operations between these
FileHandler
implementations?
- Am I getting the same sort of data from the different sources (e.g. Is where you get the data from a separate concern to what the data is).
Initially it may seem like the first question should be answered with "No", especially when you are thinking about methods such as getExcelData(String filePath, String workSheet, String row, String column)
.
However, if the data is similar then you might then start to experiment with different ways to represent a getData
method that is common across implementations, so perhaps something like:
The interface
public interface FileHandler {
public byte[] getData();
}
The Excel implementation
public class ExcelHandler implements FileHandler {
private String filePath, workSheet, row, column;
public ExcelHandler(String filePath, String workSheet, String row,
String column) {
// Set the local vars
..
}
// Pseudo code with no exception handling - yuck!
@Override
public byte[] getData() {
File excelSheet = ApacheCommonsFileLoader.loadFile(filePath);
return ExcelPOIAPI.readCell(workSheet, row, column);
}
}
The Word implementation
public class WordHandler implements FileHandler {
private String filePath;
public WordHandler(String filePath) {
this.filePath = filePath;
}
// Pseudo code with no exception handling - yuck!
@Override
public byte[] getData() {
return WordPOIAPI.readDoc();
}
}
The Tests
// Very rough crappy test, note the explicit creation of the ExcelHandler
@Test
public void testGetDataForExcel() {
FileHandler fileHandler = new ExcelHandler("foobar.xls", "foobar", "A" "23");
assertNotNull(fileHandler.getData());
}
// Very rough crappy test, note the explicit creation of the WordHandler
@Test
public void testGetDataForWord() {
FileHandler fileHandler = new WordHandler("foobar.doc");
assertNotNull(fileHandler.getData());
}
The client
// Very rough crappy client, the fileHandler being passed in
// was previously created, see explanation below
public void processData(FileHandler fileHandler) {
byte[] data = fileHandler.getData();
// Do stuff with data
}
The question you might ask yourself is then "How/where do I create the specific type of FileHandler I want?". Commonly you can hard code it (like I did in the tests), use a Factory, or use Dependency Injection (DI) via an IoC framework such as Guice, Spring or PicoContainer. DI is all the rage at the moment (please use it lightly and wisely) so that might be something for you to explore (I highly recommend Guice for learning this).
Hope that helps a little!