api workshop: deep dive into java

63
API Documentation Workshop: Deep Dive into Javadoc By Tom Johnson www.idratherbewriting.com January 24, 2015

Upload: tom-johnson

Post on 16-Jul-2015

1.074 views

Category:

Technology


3 download

TRANSCRIPT

API Documentation Workshop: Deep Dive into Javadoc

By Tom Johnson

www.idratherbewriting.com

January 24, 2015

Tech writer as lolcat

Sample Javadoc comment

Browse a full example from

Oracle. See the “Examples of Doc

Comments” section.

http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#examples

Full Javadoc example

Java documentation itself is created with Javadoc (obviously).

http://docs.oracle.com/javase/7/docs/api/

Workshop sample code

Workshop sample Javadoc

Default output from the standard Java doclet that parses

Javadoc tags.

How to import sample Java project

1. In Eclipse, go to File > Import.

2. Expand General, select Existing Projects into Workspace. Then click Next.

3. In “Select Root Directory,” select the sample_java_project folder in the workshop files.

4. Click Finish.

5. In the project, expand the javadoc_tagspackage and click the .java files to view them.

Who uses Java + Javadoc

• Used by Java developers.• The most common document generator for Java

APIs.• Supported by Oracle.• Integrates directly into IDE that developers use.• Format is familiar to Java developers.• Output is skinnable but you can’t add non-ref

files to it.• Comment style is highly similar to most other

document generators.

Do developers write the initial API documentation in the source code?

Yes No Sometimes

28%

29%

30%

31%

32%

33%

34%

35%

36%

37%

Who writes the Javadoc?

• Often engineers write reference documentation, but the Javadoc is often incomplete, unclear, inconsistent, or otherwise problematic.

• Some power API writers/developers might look at the source code and create documentation from scratch, but this is less common.

Can tech writers contribute to Java reference doc?

• Java libraries are highly technical. You must understand Java to contribute substantially.

• One of the things tech writers can contribute is style, says Joe Malin.

• Javadoc style is highly structured. You’re not just editing grammar.

What to look for in Javadoc

1. Missing doc. Lots of Javadoc is incomplete. Look for missing documentation.

2. Consistent style. See if the existing tags follow Java’s style conventions.

3. Clarity. Some descriptions are unintelligible due to the curse of knowledge, but it’s hard to judge without a stronger grasp of Java.

Note: Only public classes, methods, and fields get included in the Javadoc, so focus on these.

Install Eclipse IDE for Java developers

You need an IDE to work with Java source files. Eclipse contains the JDK. Eclipse is the

most common.

Install the Java Development Kit (JDK)

The JDK is included in Eclipse, but the JDK includes the JRE,

which you may or may not have. Type java -version

to check.

Install Git

You get source files using source control

such as Git, Mercurial, Perforce, etc. (Type

which git to see if you already have it.)

Developers get files through source control software

Copy the clone URL and enter git clone

{url} in a Terminal prompt, replacing

{url} with the actual URL. https://github.com/tomjohnson1492/apiworks

hop

Activity: Get source code

1. Open command prompt or terminal, cd to a convenient directory, and type git clone https://github.com/tomjohnson1492/apiworkshop

2. Open Eclipse, then File > Import > General and select Existing Projects into Eclipse.

3. Select the directory for the eclipse project you downloaded in step 1.

Javadoc overview

There’s no search, but there is an index. You can choose frames or

no frames.

Browse classes from left pane (All classes) or

by package. When browsing by package, you see a summary of all classes contained in

that package.

Each class has 3 main sections

Each class in the Javadoc has 3 main

sections: Fields, Constructors, and

Methods. They have a summary first and then link to detailed sections

for each below.

Easy way to preview Javadoc

• Look in Javadoc pane at bottom of screen while using Eclipse.

The Javadoc tab lets you preview what the Javadocoutput will look like. Shows only the element your cursor is on.

Java classes

• Classes are templates from which objects are constructed.

• Analogy: You download a resume template in Word, and then use it to create your own resume.

• The resume template still exists, but now you have an instance/object from the template that contains all the styles and elements from the template.

Java classes (cont.)

• Another Example: From a Bicycle blueprint, you make 3 three bicycle objects: Trek, Raleigh, and Giant.

• The Bicycle class has a field called size and a method called roll.

• So each bicycle object inherits the size field and the roll method.

• Each object is independent of the class.

Common terms

• “Instantiation” is the process of creating an object (an “instance”) from a class.

• When you “instantiate an object,” or “instantiate the class,” it means you’re creating creating an object from a class.

• Classes are organized into packages (folders).

What a class looks like

public class ACMESmartphone {

// fields

// methods

}

Classes always say “class.” They have the same name as the file, and start with a capital letter. They don’t take

arguments, so no parentheses () appear after the class name.

“Public” is an access modifier that defines who can access this

class. All public classes are included in Javadoc. Private classes are not.

The main method

• In the sample files, the App.java class contains the main method:

public static void main(String[] args) { }

• The compiled Java program will look for the class containing the main method and the code there.

• Note: The App.java class isn’t meant to be included in the Javadoc. Users will have their own application code where they call the Java classes from our Java API.

Javadoc tags versus comments

/**

*

*

*

*/

/*

*

*/

//

A slash followed by two asterisks indicates Javadoc content.

Just one asterisk is a regular comment. Or

two slashes.

Class description/**

* Works like a regular smartphone but also tracks roadrunners.

* <p>

* The ACME Smartphone can perform similar functions as other smartphones, such

* as making phone calls, sending text messages, and browsing the web. However,

* <p>

* Note that the RoadRunner Tracker app requires you to be connected to wifi. It

* will not work on cellular data.

*

* @author Tom Johnson

* @version 2.0

* @since 1.3

*/

public class ACMESmartphone {

// content for class …

}

• Javadoc content appears before the class.

• Short description ends with first period. Long description then begins.

• Use <p> for paragraph breaks.

• Tags come at end.• HTML tags allowed

(e.g., <code>, <ul>)

Short description

Short description of the class appears on Class

Summary section of the package overview.

Short + long description

Both short and long descriptions appear on the

class page.

Available tags for the description

/** @author Joe Developer* @version 2.0* @see Dynamite* @since 1.3* @deprecated Use the {@link Dynamite class instead}*/

@param and @throws are used in methods rather than

classes.

See = “See also”Since = when the class was first included

Generating Javadoc

1. Go to File > Export.2. Expand Java and select

Javadoc. Click Next.3. In left pane, select the

project & package you want.

4. In the right, select the check boxes next to the classes you want.

5. Click Finish.

Packages are folders for classes

This javadoc_tags package has two classes, summarized here.

Activity: Generate a Javadoc

1. Go to File > Export.

2. Select Java > Javadoc, and click Next.

3. Select javadoc_tags and expand it.

4. Select Dynamite and ACMESmartphone class check boxes.

5. Click Finish.

6. Compare how the classes listed in the source end up in the Javadoc.

Fields

• Fields are variables available to the class.

• Don’t use any @ tags for fields -- descriptions only.

• Only public fields are included in Javadoc. (If there is no access modifier, the default is package-private, not public.)

• Many times fields are “encapsulated” with getter-setter methods, which means their values are set in a protected way.

Sample field

/**

* The coordinates where the nearest roadrunner is located.

*/

public String LongLat = "Longitude = 39.2334, Latitude = 41.4899";

Almost everything has an access modifier (public, private) and a data type (String, int).

Constructors

• Constructors are methods that create objects.

• Constructors have the same name as the class, but with () for arguments.

• Constructors initialize objects with values passed from arguments.

• It’s a best practice to include a constructor even if it’s just the default.

Sample constructor

public class ACMESmartphone {

public ACMESmartphone(double model, String license) {this.model = model;this.license = license;

}

}

Constructors have the same name as the class, but they don’t say “class” and they have () for arguments.

When this ACMESmartphoneclass is instantiated, it will be initialized with model and license values.

Sample constructor in action

public class App {

public static void main(String[] args) throws IOException {

ACMESmartphone myACMESmartphone = new ACMESmartphone(2.0, "398978fdskj");

}

}

You create a new object called myACMESmarpthonehere. It’s a new instance of the ACMESmartphoneclass.

Java methods

• Methods are subprograms that a class can do.

• Methods take arguments.

• Methods often return values to their caller.

Example: A calculator class might have the methods add, subtract, divide, multiple.

add(a, b) {

sum = a + b;

}

Sample method

public class ACMESmartphone {

public String findRoadRunner(String city, String state) {

System.out.println("location: " + city + ", " + state);

// more logic…

}

} Methods appear inside of classes. They begin with lowercase and follow camelcase style.

Methods accept arguments. The arguments get passed into the logic of the method’s program.

/*** Gets the geocoordinates of roadrunners based on your city and

state.* * @param city the city you want to browse for roadrunners* @param state the state you want to browse for roadrunners* @return the coordinates of the roadrunner in your area* @throws IOException if you put integers instead of strings*/

public String findRoadRunner(String city, String state) {

System.out.println("location: " + city + ", " + state);System.out.println("getting geocoordinates of roadrunner.... ");System.out.println("roadrunner located at " + LongLat);return LongLat;

}

Documented method

Descriptions for methods are similar to classes. But @ tags include param, return, throws. The method’s code must match the tags or you get warnings in Javadoc.

@param tag guidelines

@param fuseLength the length of the fuse on the stick of dynamite

• @param is followed by parameter name• Don’t specify data type since it’s shown in the

method’s arguments• Written as a lowercase phrase, without a period• If multiple parameters, arrange by order or

arguments in the method• Required even if no descriptions are present• Validated against code so doc must match

Activity 2

1. Look at the location of the params in the java source code. Find the same params in the Javadoc output.

2. Look at the location of the method descriptions in the Java source code. Find the same descriptions in the output.

3. Look at the location of the return tags in the java source code. Find the same returns statements in the output.

@return tag guidelines

@return the image at the specified URL.

• At end of method, return means it returns this value to the method that called it.

• Methods that don’t return anything have a “void” modifier.

• Not followed by a specific word like @paramis.

• Code must actually return something in order for this to validate in javadoc.

@throws tag guidelines

@throws IOException if your input format is invalid

• Means if something goes haywire in the code, Java will flag the problem with a specific type of error in the error message.

• You add @throws tags to methods only if the method throws a specific error. Helps to pinpoint problems in code.

• Written with “if clause” as a continuous full sentence.

• Synonymous with @exception.

Adding links

• You can add links through the @link tag.

{@link Foo}

{@link Foo#bar}

Here “Foo” is the class name, “bar” is the method name.

Don’t overpopulate docs with links, though. Use <code> tags to set off class or method names.

Javadoc checks to see if tags match code

The code doesn’t have a blackPowderparameter in the method, so Javadoc creates an error when generating doc.

Activity: Add a field and method

1. Add an additional @param tag to the Javadoc.

2. Regenerate the Javadoc.

3. See if Javadoc generates an error and warning for the mismatched documentation.

For more detail on Javadoc, see Oracle’s Javadoc guidelines page

Also see http://idratherbewriting.com/java-javadoc-tags/ for my own summary.

Recognize these Java terms

1. Class: blueprints for something

2. Object: an instance of a class

3. Methods: what the object/class can do

4. Fields: variables in the object/class

5. Constructor: a method to create an object for a class

6. Package: a folder that groups classes

7. Access modifier (e.g, public): the scope at which a thing can be accessed

8. Interface: a skeleton class with empty methods (used for standardizing)

9. Enum: a data type offering predefined constants

10. Subclass: a class that inherits the fields + methods of another class

11. JAR file: a zip-like file containing Java classes

12. WAR file: a compiled Java web application to be deployed on a server

13. Doclet: what parses the Javadoc tags and produces the Javadoc output

Activity: Add some content

1. Add a new method to one of the classes by copying an existing method and changing some of the content. (Keep the access modifier as public.)

2. Modify the description, some parameters, and return value for your new method.

3. Generate the Javadoc and see your newly documented method.

Doxygen

- Commonly used for C++.- Works with Java, C++, C#, and others.- Has easy front-end GUI.- Point it at your source files.- Automate into builds.- Can include non-source files (Markdown).- Frame-based output.- Can skin.

Doxygen has GUI front-end

Specify the source directory of your files.

PITFALLS WITH AUTO-DOC TO WATCH OUT FOR

Cons of in-source documentation

1. Subject to Curse of Knowledge

2. Not task-focused

3. Suffers from lack of ownership

4. Doesn’t integrate with other content

5. Gives illusion of having real doc

Since the reference doc is often written partly by engineers, you have to watch out for several pitfalls

A developer who creates the API may assume too much of the audiences’ technical ability. As a result, the descriptions aren’t helpful.

Problem 1: Curse of Knowledge

Auto-doc is feature-based doc approach. Task-based doc includes multiple calls and workflows in support of goals. It might make use of several different objects and methods across the reference doc.

Problem 2: Not task-focused

Problem 3: Lack of ownership

Auto-doc is a stray dog.

Auto-doc is owned like a stray dog or wiki is owned. Someone may contribute some food or a page without care for the whole. Usually there isn’t a developer overseeing all the doc. Tech writers feel less responsible when auto-doc is a separate from their output.

Problem 4: Doesn’t integrate

Auto-doc doesn’t integrate directly into a website except as a link from your other web pages. Like a HAT-produced webhelp file, the auto-doc is its own little website.

Problem 5: Gives illusion of real doc

“… auto-generated documentation is worse than useless: it lets maintainers fool themselves into thinking they have documentation, thus putting off actually writing good reference by hand. If you don’t have documentation just admit to it. Maybe a volunteer will offer to write some! But don’t lie and give me that auto-documentation crap”. – Jacob Kaplan Moss

Looks real but isn’t.

Still, auto-doc is the way to go

1. Takes a complicated set of Java elements and formats them in a predictable, easy-to-read way that Java developers are familiar with.

2. Provides documentation directly in the IDE, along with tooltips and other helps while developers are coding.

3. Reduces documentation drift and prompts developers to add documentation for features they add with each commit.

Tom Johnsonhttp://idratherbewriting.com@tomjohnson

Image credits

• Slide 2: Lolcat Generator: Can haz posters? http://bighugelabs.com/lolcat.php

• Slide 55: Biodiversity fail. By Martin Sharma. Flickr. http://bit.ly/1CodnKM

• Slide 56: The Source of Bad Writing. Wall Street Journal. http://online.wsj.com/articles/the-cause-of-bad-writing-1411660188

• Slide 58: Stray dog. By Jose Javier Perez Arenas. Flickr. http://bit.ly/1wau5NK

• Slide 60: The false. By Cristopher Cotrell. Flickr. http://bit.ly/1F1et36. Quote from Jacob Kaplan Moss here: http://jacobian.org/writing/what-to-write/