Interfaces vs. abstract classes
Received this question as an e-mail:
This is regarding the section Public instance methods should be part of an interface.
I couldn't find any mentioning of abstract classes as alternative to class interfaces in the document. I have good experiences with abstract classes and inheritance and don't see that public methods must be part of the interface, as stated here. What are the arguments against using abstract classes instead of interfaces?
IMHO the main argument is protocol enforcement. An interface can't possibly inherit anything. A virtual class is one click away from becoming instantiable. And is relatively easy to use code which was not supposed to.
As an example, I create an abstract class and derive an child for real usage and one for unit testing. Then someone either:
- adds some SQL in the virtual class -> my tests now are database dependent and maybe even alter it
- adds an utility method as public (perhaps so it can be tested) -> interface pollution
Both problems are easy to avoid if everyone knows and follows the rules, but it's a big if
If I have code I want to share between implementations I'd rather put it in another class which then I call from the real implementation, but I don't want parent relations between my test and real classes
Was fixed with #75