code documentation. that ugly thing
TRANSCRIPT
Code Documentation. That ugly thing..
Manios Christos
Thessaloniki Java Meetup Group
2014-11-28
1. Introduction
What is code documentation
Written specifications, instructions, logic, proof of concept of source code so it is readable by:– Humans– machines
Why is it important?
A contract between callers and implementors. We continuously stumble upon it! It may be annoying. We argue about it!
– Σημείον αντιλεγόμενον.– The reason of this presentation!
Let's argue!
Opposition arguments Running out of time! Not my responsibility.. The others do not document. Why should I do it? I remember what I am coding! We are not Google! (or Microsoft, Pivotal etc.) Who is going to read it? If I do not document, I shall be irreplaceable.
Pro documentation arguments (1)
Documentation ..
reminds you of what you code Helps in IDE autocompletion functionality. Creates a pleasant mood to your code editor / reviewer / colleague. Provides proof of your code quality (run / fail) . Reduces time spent on helping colleagues understand your code.
– Res ipsa loquitir (the thing itself speaks)
Pro documentation arguments (2)
Documentation ..
Generates legible Javadoc output Reduces rage, curse “generation” and negative emotions of your code
reviewer / editor / project colleague! Helps project documentation writer’s work. (Who is this??) Helps building productive, geographically distributed teams.
Pro documentation arguments (3)
Documentation ..
Advertises your work (and consequently yourself)! Makes your product more competitive to other products. Makes your code suitable for contributing in Open Source projects.
2. Javadoc
What is Javadoc
Javadoc is the style guide, tag and image conventions we use in documentation comments for programs written in Java.
Javadoc guidelines
The following slides contain standards, guidelines and tips from:
Oracle Javadoc Google Java Code style Joda Time (Stephen Colebourne's notes)
Javadoc guidelines (2)
Be aware of the following:
Write Javadoc to be read as source code Use standard style for Javadoc comment: /** bob */ Define a punchy first sentence Define clearly the required/allowed variations across
platform/implementations.
Package documentation
Create a file named package-info.java in every package:
(Example from Android SDK)
/** * Contains the SQLite database management classes * that an application would use to manage its own * private database. * Applications use these classes to manage private * databases. */package android.system.sqlite;
Documenting classes
The Javadoc for each class and member begins with a brief summary fragment.
This is a fragment—a noun phrase or verb phrase, not a complete sentence
It does not begin with A {@code Foo} is a..., or This method returns...
nor does it form a complete imperative sentence like Save the record..
However, the fragment is capitalized and punctuated as if it were a complete sentence.
Documenting classes
Lets see an example:
(Example from Android SDK)
/** * Exposes methods to manage a SQLite database. * <!-- skipped some content --> * <p>In addition to SQLite's default <code>BINARY</code> * collator, Android supplies * two more, <code>LOCALIZED</code></p> * <!-- […] ---> */public class SQLiteDatabase extends SQLiteClosable {
Documenting interfaces
Same as class javadoc. Specify a brief definition :
/** * Interface for generic CRUD operations on a repository for a specific type. * * @author Oliver Gierke * @author Eberhard Wolff */@NoRepositoryBeanpublic interface CrudRepository<T, ID extends Serializable> extendsRepository<T, ID> {}
(example from spring-data-commons)
Documenting Methods
Use a striking first sentence Method descriptions begin with a verb phrase. Use 3rd person (descriptive) not 2nd person (prescriptive). Use @param, @return and @throws Javadoc has to be present at the minimum in every public or protected
member of the class. Exceptions:
Self explanatory methods (handle with caution!!). Overrides of supertype members.
Documenting Methods: Example 1 (bad)
Do not forget to use standard javadoc comments
(Example from Android SDK)
// Begins a transaction. Transactions can be nestedpublic void beginTransaction() {
// your code}
Documenting Methods: Example 1 (good)
Do not forget to use standard javadoc comments
(Example from Android SDK)
/** * Begins a transaction. Transactions can be nested. */public void beginTransaction() {
// your code}
Documenting Methods: Example 2 (bad)
Avoid - The description below says nothing beyond what you know from reading the method name.
Lazy use of JAutoDoc.
(Example from Oracle Javadoc guidelines)
/** * Sets the tool tip text. * * @param text * the text of the tool tip */public void setToolTipText(String text) {
// your code}
Documenting Methods: Example 2 (Good)
(Example from Oracle Javadoc guidelines)
/** * Registers the text to display in a tool tip. * The text displays when the cursor lingers * over the component. * * @param text the string to display. If the text is * null, the tool tip is turned off for * this component. */public void setToolTipText(String text) {
// your code}
Documenting Methods: Example 3 (bad)
Do not forget to mention extra capabilities of the parameters.
/** * @param zkHost The client endpoint of the zookeeper quorum * containing the cloud state, in the form HOST:PORT. */
public CloudSolrServer(String zkHost) {// SolrJ code for constructor
}
(Example from CloudSolrServer (SolrJ 4.9.0). )
Documenting Methods: Example 3 (better)
Personal modification: Clarify parameter variations.
/** * @param zkHost * The client endpoint of the zookeeper quorum * containing the cloud state, in the form HOST:PORT. * * <p>It can contain multiple definitions in the form of * <code>HOST1:PORT1, HOST1:PORT2, HOST2:PORT2<code></p> */public CloudSolrServer(String zkHost) {
// SolrJ code for constructor}
(Example from CloudSolrServer (SolrJ 4.9.0). )
Documenting Methods: Null handling
Define null-handling for all parameters and return types
“not null" means that null is not accepted and passing in null will probably throw an exception , typically NullPointerException
"may be null" means that null may be passed in. In general the behaviour of the passed in null should be defined
"null treated as xxx" means that a null input is equivalent to the specified value
"null returns xxx" means that a null input always returns the specified value
Documenting Methods: Null handling example
/** * Javadoc text. * * @param foo * the foo parameter, not null * @param bar * the bar parameter, null returns null * @return the baz content, null if not processed */public String process(String foo, String bar) {
// code}
Documenting Methods: Exceptions
Document the following exceptions with the @throws tag: All checked exceptions. Those unchecked exceptions that the caller might reasonably want
to catch
Documenting Methods: Exceptions example
/** * Adds a collection of documents, specifying max time before they become committed * @param docs the collection of documents * @param commitWithinMs max time (in ms) before a commit will happen * @throws IOException If there is a low-level I/O error. * @since solr 3.5 */public UpdateResponse add(Collection<SolrInputDocument> docs, int commitWithinMs) throws SolrServerException, IOException {
// code}
(Example from CloudSolrServer (SolrJ 4.9.0). )
Documenting Constants: Bad
Do not forget to document constants Use standard javadoc
// dial a phone number public static final String ACTION_DIAL="android.intent.action.DIAL";
Documenting Constants: Good
Make your user feel comfortable, even if you think that the constant is seld explanatory
(Example from Android SDK Intent class)
/** * Activity Action: Dial a number as specified by the data. This shows a UI * with the number being dialed, allowing the user to explicitly initiate * the call. * <!-- some content is skipped --> */@SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)public static final String ACTION_DIAL = "android.intent.action.DIAL";
Documenting Enums
There is no official reference for Enums Enums are classes, so treat them as classes!
3. Doclets
What is a doclet
Doclet is a program which works with the Javadoc tool to generate documentation from code written in Java. Doclets :
Are written in Java format the presentation of the content. create the file(s) that contains the documentation.
Java standard doclet
Comes inside JDK distribution with Javadoc tool. : Format for Java S.E. 1.6 Format for Java S.E. 1.7
If you use Maven you can invoke it using: mvn javadoc:javadoc
Doclava
Custom Javadoc doclet Refreshed look and feel Search capabilities Embeds versioning information (example: Android SDK reference) Use of templating engine for user customizations.
More information in Google Code or Atlassian Bitbucket fork If you use Maven you can invoke it using:
mvn javadoc:javadoc
4. Real world examples
(of well documented projects!)
Inspired by real world projects
This presentation would not come into life without real world examples. Inspired by well known commercial projects. Inspired by well known open source projects.
Microsoft Development Network
Also known as MSDN Commercial
BUT .NET framework has became an Open Source project!! More to come!!
Fully documented with tones of examples: Example: C# Reference documentation
HEEEEY !!! This is not Java !!! BUT it is a lucid example of well documenting software projects and programming languages.
Android OS
Open source Fully documented, with examples and tutorials:
Developer Portal Reference documentation SDK Javadoc
Apache Lucene / Solr
Open source index / search engine Project sites:
http://lucene.apache.org/ http://lucene.apache.org/solr/ SolrJ client reference: http://lucene.apache.org/solr/4_10_0/solr-
solrj/
Spring Framework
Open source Java framework Fully documented: See http://spring.io/projects
5. One step forward: Project documentation
Moving forward: Project documentation
Code documentation is not a replacement of project documentation. Javadoc may have links to project documentation. Every project should be documented. Written and updated by documentation writers (Bazinga!) Collaboration between developers and writers. Use documentation tools (not MS Word files). Use source control for documentation (Git, SVN, Mercurial)
Documentation tools
Well known documentation tools:
Markdown AsciiDoc reStructuredText Confluence
Markdown
text-to-HTML conversion tool for web writers Markdown allows you to:
write using an easy-to-read write easy-to-write plain text format then convert it to structurally valid XHTML (or HTML).Markdown
Examples: Github pages Facebook osquery wiki
AsciiDoctor
Asciidoctor is a fast text processor and publishing toolchain for converting AsciiDoc content to HTML5, DocBook 5 (or 4.5) and other formats.
Characteristics: Open source project Easier than XML based DocBook Example: Spring Data Solr Documentation
reStructuredText
an easy-to-read, what-you-see-is-what-you-get plaintext markup syntax and parser system
Easy to convert and export to other formats file format for textual data used primarily in the Python community for
technical documentation. used primarly in Sphinx documentation tool Example projects:
Python documentation MongoDB docs Varnish cache docs
Confluence
Commercial team collaboration software Used in corporate environments not only for documentation Free for Open Source Projects
Example projects: Apache Foundation Wiki
Conclusion
Do not hesitate to document your code. Establish a documentation strategy in your project / team / company. Use successful projects as examples. Let your good work speak for you.
Question Time