By Sarah Maddox | Member
As technical writers, we are trained to put ourselves into the position of the reader. In the case of API technical writing, the readers are developers looking to use our APIs and development tools.
To a developer, a code sample speaks a thousand words. Skimming code samples in a document is like skimming headings for the rest of us.
As technical writers, we are trained to create clear and meaningful content. And code is content. On the other hand, technical writers aren’t necessarily software engineers. How can we write code samples?
We don’t need to be code ninjas. The code in an illustrative sample is not the same thing as the production-ready code in an application. This article describes the nature and purpose of code samples, and gives guidelines on how to write them.
What Is a Code Sample?
A code sample is a piece of syntactically correct and semantically useful code, written to illustrate the functionality and usage of an API or a developer tool.
The code sample provides a stepping stone between the conceptual overviews in the developer’s guide, and the complex implementation required for a production-ready application.
This short-and-sweet code sample is from the documentation for the Google Maps Android API (https://developers.google.com/maps/documentation/android/map). I’ve quoted the textual instructions as well as the Java code sample used to illustrate them:
To set the type of a map, call the GoogleMap object’s setMapType() method, passing one of the type constants defined in GoogleMap. For example, to display a satellite map:
GoogleMap map;
...
// Sets the map type to be "hybrid"
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Notice a few things about the sample:
- It’s short.
- It includes an ellipsis, letting developers know that more code is likely to be needed in the actual implementation.
- Apart from the ellipsis, the code is syntactically correct, down to the semicolons.
- The author assumes some pre-existing knowledge. In this case, it’s assumed the reader is acquainted with the Java language, and with the GoogleMap class as the model of a map within an application.
- The sample nicely illustrates the textual instructions.
- The single variable in the code has a meaningful name, “map.”
- Short though it is, the code still includes a comment (the words after the double slash).
Code samples may be illustrative snippets within a tutorial or getting-started guide, like the above example. Or they may comprise a fully working demo app, usually linked from the documentation and available for download.
Let’s start with the case of the demo app, then move on to snippets.
A Fully Working App as a Getting-Started Tool
One of the main aims of a code sample is to get the developer started as painlessly as possible.
TTFHW (Time to First Hello World) is a hot topic amongst developers who use or build APIs. It’s a bit like car enthusiasts talking about “0 to 100 in four seconds.” For a happy getting-started experience, the trick is to get TTFHW as short as possible.
A Demo App Embedded into the Page
In some cases, a demo app may be very simple. For example, it’s possible to demonstrate the Google Maps JavaScript API with a scribble of JavaScript (https://developers.google.com/maps/documentation/javascript/tutorial#HelloWorld).
The following Web page displays a map centered on Sydney, New South Wales, Australia:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=SET_TO_TRUE_OR_FALSE"></script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644), zoom: 8
};
var map = new google.maps.Map(
document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window,
'load',
initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
A Downloadable Demo App
A fully working demo app may be fairly complex and the development project includes a number of files containing code, CSS, images, and other resources. The best thing is to store the app in a public repository and include a link in the documentation, so that developers can download the demo and import it into their development environment.
An example is the demo app supplied with the Google Maps Android API Utility Library (https://github.com/googlemaps/android-maps-utils/tree/master/demo). The setup guide for the library includes a description of the demo app, which is included as part of the downloadable library (https://developers.google.com/maps/documentation/android/utility/setup#demo).
Often the development team creates the demo app, or the technical writer has a lot of help in the development. Certainly the technical writer will review the code, paying particular attention to the comments, the naming of variables and methods, and the overall readability and simplicity of the sample.
Illustrative Code Snippets
The introductory section of this article included a very short code snippet. Let’s look at some further examples.
Help Developers Understand the API
To help developers get started quickly, samples may illustrate the major features and primary use cases of the API. To a developer, a code sample means more than a block of prose.
A good example is the landing page of the Google Maps Android API documentation (https://developers.google.com/maps/documentation/android/). The page includes six medium-length code samples, starting with “Hello Map” and moving on to common, popular use cases such as adding a marker to a map and drawing a line from one location to another. A particularly nice feature of the page is that each code sample is accompanied by a video showing the code in action.
Illustrate a Specific Part of the API
Other samples aim to help developers grasp the purpose and usage of a specific feature, method, or function.
Let’s take a look at the guide to marker clustering in the Google Maps Android API Utility Library (https://developers.google.com/maps/documentation/android/utility/marker-clustering). It begins with an explanation of the concept of marker clustering (a technique used to deal with a large number of place markers concentrated in a small area on a map, without making the map hard to read).
Then follows a very short step-by-step guide:
Here is a summary of the steps required:
- Implement ClusterItem to represent a marker on the map. The cluster item returns the position of the marker as a LatLng object.
- Add a new ClusterManager to group the cluster items (markers) based on zoom level.
- Set the map’s OnCameraChangeListener() to the ClusterManager, since ClusterManager implements the listener.
- If you want to add specific functionality in response to a marker click event, set the map’s OnMarkerClickListener() to the ClusterManager, since ClusterManager implements the listener.
- Feed the markers into the ClusterManager.
Next up are the code samples, interspersed with very short textual introductions. Here’s an example from the page:
In your map activity, add the ClusterManager and feed it the cluster items.
private void setUpClusterer() {
// Declare a variable for the cluster manager.
private ClusterManager<MyItem> mClusterManager;
// Position the map.
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.503186, -0.126446), 10));
// Initialize the manager with the context and the map.
// (Activity extends context, so we can pass 'this' in the constructor.)
mClusterManager = new ClusterManager<MyItem>(this, getMap());
// Point the map's listeners at the listeners implemented by the cluster manager.
getMap().setOnCameraChangeListener(mClusterManager);
getMap().setOnMarkerClickListener(mClusterManager);
// Add cluster items (markers) to the cluster manager.
addItems();
}
Points to note:
- The sample doesn’t show any of the plumbing and boilerplate code that typically clutters a production-ready application, as library import statements and routine error traps.
- The page includes the primary method that does the clustering (called setUpClusterer()) and a class that’s important for developers to understand (public class MyItem implements ClusterItem).
- Distinct bits of processing are separated out into functions and given a meaningful name: setUpClusterer() and addItems(). This helps the reader grasp the concepts.
- There are plentiful code comments.
- Syntax highlighting (different colored text for each syntactical component) improves the readability of the code and makes developers feel right at home.
Summarizing the Goals of a Code Sample
A code sample should:
- Get the developer up and running as quickly as possible.
- In combination with the textual commentary, provide high-level, conceptual information that is not easy to find by reading the in-depth reference documentation or code.
- Be syntactically correct, and thus suitable for copying and pasting into an existing project or framework.
- Work (that is, do what it’s meant to do) when dropped into a development project.
- Be as simple and clear as possible.
How to Create Sample Code
Here are 10 guidelines for creating a useful code sample:
- Find out the primary use cases for the API or tool you’re documenting. Those are what your code should illustrate. Talk to the development team and product managers and read the requirements or design document. If you’re lucky, there’ll already be some useful comments in the code, too.
- Find out what you can safely assume about your audience. Are they are familiar with the technology you’re working with (in my case, Java and Android development)?
- Find some “real” code that does something similar to what you need: perhaps a similar function, or a working implementation that you can simplify for use as a sample. Or find a developer to help you write the sample from scratch.
- Simplify the code. Remove functionality that’s unique to your environment or that adds super-duper but superfluous features. For on-page code snippets, remove plumbing, such as import statements, and all but the essential error handling.
- Make the code easy to read:
- Make names meaningful. This includes the names of variables, classes, methods, and functions.
- Keep methods and classes short. Compartmentalize logically related chunks of code into separate methods, classes, or functions, with meaningful names. This will help people grasp the concepts.
- Pay attention to the indentation of the lines of code. It should follow a standard pattern and should illustrate the logical components (class and method definitions, method calls, and so on) of the code.
- As far as possible, have all the necessary code in one piece, so that people can copy and paste easily.
- Add code comments. Developers often add technical comments to the code, but don’t include an introduction or conceptual overview of what’s going on. And our target audience, also developers, will often read code comments where they don’t read other documentation. So code comments are a great medium for technical communication!
- Put your code into a framework and test it. The framework should be one that your audience will be using. In my case, that’s an Android development project.
- Take screenshots of the code in action. They’re often useful to give people an idea of the goal of the sample code, and of what the API or tool can do.
- Get the code reviewed by the development team.
Making Your Samples Super Useful
These are extra tips for increasing the usefulness of your code samples:
- Use the terms “foo” and “bar” in the sample. Developers associate these two terms with an example. Some people even search for “foo” and “bar” plus the specific tool or API, when looking for examples. (Thanks to Sergii Pylypenko and Ben Buchanan who pointed this out in a comment on Google+ [https://plus.google.com/u/0/+SarahMaddox/posts/4oUpBs2CxAs].)
- If your content management system supports it, put the code in a source repository and auto-include sections into the documentation using a “snippet” or “excerpt” tool. There are advantages to having your code all in one place, rather than scattered across multiple documents. This is especially useful if your code is a complete demo app. Bitbucket (https://bitbucket.org/) and GitHub (https://github.com/) are examples of online repositories. GitHub offers “gists” specifically for sharing code snippets (https://help.github.com/articles/creating-gists).
- If your code is a fully working demo app, hook it up to an automated test framework to help ensure the code samples remain compatible with changes to the API or tool that they document.
This article quotes examples from the documentation for the Google Maps Android API (https://developers.google.com/maps/documentation/android/) and the Google Maps JavaScript API (https://developers.google.com/maps/documentation/javascript/). Thanks to Google for sharing this work (https://developers.google.com/site-policies), which is used according to terms described in the Creative Commons Attribution 3.0 License (http://creativecommons.org/licenses/by/3.0/). Note that the documentation is under continuous development, as the Google Maps APIs release new features and improvements. This means that the text or code may have changed since this article was written.
Sarah Maddox is a technical writer in the Developer Relations team at Google. Before becoming a Googler, Sarah worked at Atlassian and various other companies in Australia, the UK, the Netherlands, and South Africa. With around 15 years of technical writing under her belt, and 9 as a software engineer, she has a history of persuading words and code to play nicely together. Sarah’s blog is ffeathers.wordpress.com.