Source Code – Is Reading Javadoc Preferable to Reading Source Code?

commentsjavadocssource code

I just came across the following in a lab manual at university:

You do need to study the interfaces of the classes by generating the javadoc for them so you know what operations are provided (feel free to look at the code, but
when using somebody else’s code, as here, you should work from the javadoc rather than the code whenever possible).

I don't understand why this is the case; since the javadoc could be out of date, or could describe the function of the code badly. Surely looking at the source code, and reading the javadoc comments is best?

Is there a reason why, or a case when reading only the javadoc is the best thing to do?

Best Answer

The recommendation is probably about programming to an interface rather than the implementation.

Sure, if you have access to the code then there's nothing stopping you from looking at the implementation to understand how it works. But you should always make sure that the how doesn't influence your consumption of the API.

When you're consuming an API you're working against an abstraction. Try to concern yourself only with what the API offers (the contract) and not the how (the implementation).

This is because there is no guarantee that an API's implementation won't change drastically from one version to the next, even if the contract has remained unchanged.

Related Topic