DEV Community

Discussion on: Doctests, the shy giant of testing modules

Collapse
perigk profile image
Periklis Gkolias Author

When you say'a function not worth a test case', what makes it need a doctest case?

Thread Thread
adambrandizzi profile image
Adam Brandizzi

Well, no function needs a doctest but, in my experience, it is useful to put a doctest in every function. Even the smallest private functions. For three reasons:

  1. We get documentation. With a doctest, we have a basic explanation of how we expect the function to be used, naturally. Even if the function is not published, it will be helpful when you're maintaining code that uses the function. And it helps a lot to reuse the code.

  2. We get some tests. The most basic behaviors of the function are now protected against unintended changes. If we have to handle a new corner case, we can add it to the doctest as well and ensure it will be preserved.

  3. And finally, the least obvious one: we get a better function. If we force ourselves to doctest a function, we find ourselves working to make it more documentable. Some lazy decisions we could take (relying on globals, mixing I/O and processing etc.) are not that convenient anymore. Our function got more and better seams, is easier to call and is more predictable.

Again, this is my experience after trying an unorthodox approach. Would you try it to be if it is true? :)