PHP Comments – Are Docblock Typehints Redundant with Strict Typing?

commentsPHP

I have a quite large private codebase which has evolved for about ten years now. I'm not using phpDocumentor but since using docblock sections has become quite the standard in open source projects I have adopted writing docblocks for all public methods in my repository as well. Most blocks just contain a small description and typehints for all parameters and the return type.

With the arrival of static analysis, these typehints have helped me a lot finding inconsistencies and possible bugs. Lately I've converted the entire codebase (Now running on PHP7.2) to have all parameters and return values type-hinted where possible, using PHP's typehints. And now I am wondering… Aren't these docblock typehints redundant? It asks quite a bit of work to keep all docblocks in sync with the ever changing code and since they don't add any new information I am wondering whether it is better to completely remove them or not.

In one hand, removing documentation feels bad, even when it is redundant. In the other, I really feel like breaking the Do-Not-Repeat-Yourself-principle everyday type-hinting stuff that is already type-hinted.

Best Answer

Information that can be found in the code should not be duplicated in comments.

At best, it's wasted effort to keep them synchronized. More likely, they will get out of sync eventually. At that point, they are just confusing.

If you look at the DocBlock equivalent in statically typed languages (e.g. Java, C#), you will find that doc comments do not contain type information. Insofar as this is the case in your PHP code, I'd strongly advise to follow suit. Of course, where type hinting cannot be applied, a comment is still your best alternative.

This is not relevant to PHP, but duplicated type information can make sense when the type is implicitly inferred (e.g. Haskell).

Related Topic