How do you decide what to abstract, and what makes an abstraction worth the extra layer?
You abstract when two or more parts of the program need to do the same job in different ways, and when the caller does not need to know which way it was done.
So here is the test that works most of the time. If you find yourself writing an if that checks what kind of thing you have, and then does different work in each branch, that is a sign that the thing should be behind an interface.
// Before: the caller has to know what kind of storage it has.
if (store instanceof DatabaseStorage) {
DatabaseStorage db = (DatabaseStorage) store;
db.save(key, value);
} else {
Map<String, String> map = (Map<String, String>) store;
map.put(key, value);
}
// After: the caller just calls the method.
store.save(key, value);
And there are four questions you can ask to decide whether an abstraction is worth the extra layer.
the question a good answer
--------------------------------------------- ----------------------
Is there more than one implementation? yes, then it pays
Do I need to test this without the real thing? yes, then it pays
Does the caller care about the details? no, then it pays
Is the interface smaller than the details? yes, then it pays
And there is one thing that makes an abstraction not worth it. If the interface has as many methods as the implementation has, and it just passes everything through, then it is an extra layer with no benefit. That is sometimes called an anemic interface and it is common in code that was written by following a rule without thinking about it.
a useful abstraction a useless layer
------------------------------ --------------------------------
three methods, many ways to one method that does the same
do the job thing as the thing behind it
hides the interesting part hides nothing
the caller gets shorter code the caller gets longer code
And there is a third thing to think about, and it is about where you draw the line. The interface should describe the job and not the data. So a Storage interface with save and load is a good abstraction, because it describes the job. An interface with getFileHandle and setFileHandle is a bad one, because it describes the data and forces every implementation to have the same shape.
So the rule to remember is this. Abstract when the details can change or vary, and keep the interface about the job.
The next two questions in this topic show the database example and the difference between an abstraction and an implementation detail.