If a class extends a parent which defines an interface, should that class also explicitly implement the interface?
As an example, is it better to include or remove the portion in square brackets below:
interface IVerbable {}
abstract class BaseVerber implements IVerbable {}
class Verber extends BaseVerber [implements IVerbable] {}
Functionally, there is no difference in forced implementation, since Verber
“is-an” IVerbable
by virtue of it’s parentage, even if it doesn’t explicitly implement the interface itself:
var_dump(new Verber() instanceof IVerbable); // bool(true)
Non-functionally, there seem to be two benefits to implementing in both places:
- A person reading the code immediately knows that it implements the interface, without having to view the parent’s definition.
- Second, PhpDocumentor doesn’t follow the trail if the abstract class doesn’t give a default implementation of the interface. The concrete implementation would not inherit the documentation unless either it explicitly implements the interface, or the abstract gives an implementation, even an empty one.
I suppose it might be bad practice to omit implemented methods from the abstract class though. It’s probably better to at least show the empty signature, but then you’re also just duplicating the empty signature in both the interface and the abstract class.
I my opinion you shouldn’t add the second implements IVerbable
. Here is why:
- It does not change the meaning of the code.
- It is perfectly natural to navigate between classes when you try to understand someone else’s code. You will have to do that anyway.
- It is the feature of the base class that it implements the interface, what the derived class inherits like everithing else. I does not make sense to repeat, as it does not make sense to repeat any other feature from the base class.
- I am not familiar with PhpDocumentor, but it does not seem like a good idea to change your code just so a tool can understand it better. (If a tool can’t understand your code because you did not followed some generally accepted and advisable convention, that is a different case.)
3