I’m designing a file handler interface:
public interface FileHandler
{
public void openFileHandler(String fileName);
public void closeFileHandler();
public String readLine();
public String [] parseLine(String line);
public String [] checkLine(String line[]);
public void incrementLineCount();
public void incrementLineSuccessCount();
public void incrementLineErrorCount();
public int getLineCount();
public int getLineSuccessCount();
public int getLineErrorCount();
}
It is soon apparent to me that these methods can’t be made private. I don’t want incrementLineCount to be public.
What is proper way to design an interface like this?
5
An interface specifies behavior, not specific implementation details.
You should specify the operations you want anything that implements your interface to support. One way of determining that is asking “How will consumers use my interface; what is the contract I am specifying?”
Leave the details (e.g. the private methods) up to the implementations. That’s the point of interfaces — you can have different implementations that behave in different ways, e.g. the difference between reading a file off disk and reading a file off the cloud….
Interfaces should be designed by keeping in mind what outside objects will need to call on classes that implement the specific interface.
This is just what the class should be able to do from the outside. For everything else you can use abstract classes with protected methods (so you will have the same commodity to force implementation in subclasses but without being forced to let them public).
Something like:
interface FileHandler {
public void openFileHandler(String fileName);
public void closeFileHandler();
}
abstract class AbstractFileHandler implements FileHandler {
...
protected abstract void incrementLineCount();
protected abstract void incrementLineSuccessCount();
protected abstract void incrementLineErrorCount();
}
class ConcreteFileHandler extends AbstractFileHandler {
...
}
If you don’t need to have a common ancestor just declare the private methods in your concrete class and you are done.
2