How to write sample code

Technical writers often need to create sample code, to illustrate the primary use case of an API or developer tool, and to help developers get started quickly in the use of the API or tool. Here are some tips on how to go about creating that code. I’ve jotted down everything I can think of. If you have more tips to add, please do. :)

I recently published a set of documentation on a utility library created by Chris Broadfoot, a Google developer programs engineer. The utility library is an adjunct to the Google Maps Android API. The documentation includes an overview of all the utilities in the library, a setup guide, and an in-depth guide to one of the utilities. (I’ll document more of the utilities as time goes on.) As part of the guide to the marker clustering utility, I created some sample code that illustrates the most basic usage of the utility and gets developers up and running fast.

Quick introduction to the API and the utility library

The Google Maps Android API is for developers who want to add a map to their Android apps. The API draws its data from the Google Maps database, handles the displaying of the map, and responds to gestures made by the user, such as zooming in and out of the map. You can also call API methods to add markers, rectangles and other polygons, segmented lines (called polylines), images (called ground overlays) and replacement map tiles (called tile overlays). It’s all in the API documentation.

The utility library is an extra set of code that developers can include in their Android apps. It includes a number of useful features that extend the base API. One of those features is “marker clustering”. The full list of features is in the utility library documentation.

The marker clustering utility

The sample code illustrates the marker clustering utility in Chris’s utility library. So before diving into the code, you be asking:

What’s “marker clustering”?

Let’s assume you have a map with a large number of markers. (Typically on a Google Map, a marker is one of those orange pointy droplets that marks a place on the map.) If you display all the markers at once and individually, the map looks ugly and is hard to grok, especially when the map is zoomed out and many markers are concentrated in a small area. One solution is to group neighbouring markers together into a single marker icon (a “cluster”) and then split them into individual marker icons when the user zooms out or clicks on the cluster icon. That’s what Chris‘s marker clustering utility does.

What does marker clustering look like? See the screenshots in the documentation.

Developers can implement the classes Chris has created and customise the appearance and behaviour of the clusters. The utility library also includes a demo app, containing sample implementations of the utilities.

The sample code

The best way to describe a code library is to provide sample code. I created a simple marker clustering example, based on the demo app. Take a look at the sample code in the documentation section on adding a simple marker clusterer.

Now compare it to the code in the demo app that’s part of the utility library: ClusteringDemoActivity.java

The differences, in a nutshell:

  • The sample code doesn’t show any of the “plumbing”, such as the library import statements.
  • The sample code does include a listing of both the primary method that does the clustering (called “setUpClusterer()“) and a class that’s important for developers to understand (“public class MyItem implements ClusterItem“).
  • Instead of reading input from a file, the sample code includes a method called “addItems()” to set up some sample data directly from within the code.
  • I’ve added plentiful comments to the sample code, explaining the bits that are specific to marker clustering or the sample itself.

In summary, the sample code provides all the developer needs to get a simple marker clusterer working, just by copying and pasting the code into an existing Android project.

How to write sample code

While writing the sample code, a thought struck me:

Hey, it’s actually quite an interesting process writing sample code. I’ll blog about what I’m doing here, and see what other technical writers have to say about it. :)

First, a stab at defining the goals for the sample code:

  • Get the developer up and running as quickly as possible.
  • Be suitable for copying and pasting.
  • Work (do what it’s meant to do) when dropped into a development project.
  • Be as simple as clear as possible.
  • Provide information that is not easy to find by reading the code.
  • Illustrate the primary, basic use case of the API or tool.

And here are my jottings on how to go about creating a useful code sample:

  • Find out what the primary and simplest use case is. That is what your code should illustrate. Talk to the engineers and product managers, read the requirements or design document, read the code comments.
  • Find out what you can safely assume about your audience. Can you assume they are familiar with the technology you’re working with (in my case, Java and Android development)? Do you know which development tools they are using?
  • Find some “real” code that does something similar to what you need. Perhaps a similar function or a working implementation that’s too complex for your needs.
  • Simplify it. Make names more meaningful. Remove functionality that’s unique to your environment or that adds super-duper but superfluous features. Remove plumbing such as import statements and all but the essential error handling.
  • Put your 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.
  • Include it in the doc.
  • If possible, put the code in a source repository and hook it up to some automated tests, to help ensure it will remain current.
  • As far as possible, have all the necessary code in one piece, so that people can copy and paste easily. This may mean moving stuff around.
  • Add code comments. Engineers 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, developers, will often read code comments where they don’t read other docs. So code comments are a great medium for technical communication!

Perhaps the most important thing to do is to see yourself as the advocate for or representative of those developers who need to use the API or tool you’re illustrating. Think what questions they would ask if they had access to the people and tools that you do, and put the answers into the documentation and sample code.

Conclusion

To do this job, tech writers need a certain level of coding knowledge, and also a good understanding of what a developer needs to get started. The sample code provides a stepping stone between the conceptual overviews and the complex implementations.

Well, that’s all I can think of. What have I forgotten? :)

About these ads

About Sarah Maddox

Technical writer, author and blogger in Sydney

Posted on 21 December 2013, in Android API, APIs, Google, Google Maps, technical writing and tagged , , , , . Bookmark the permalink. 7 Comments.

  1. Great article, Sarah! Excellent overview of the issues involved in writing sample code, and tips on what to do. I’m of two minds about including import statements. On the one hand, they clutter the example; on the other hand, they make help make clear what libraries are needed to run the code, and make the sample self-contained. I like idea of a streamlined example in the text, linked to a full, runnable example on a code repo.

    • Hallo Janet

      That’s a great point. Some documents include only small snippets of code, and point to the repo for the full sample. That works very well too.

      Some IDEs automatically prompt you with the import statements required. Eclipse is very good at that. It even has a magic key combination (Ctrl+Shift+O on Windows or Cmd+Shift+O on a Mac) that will automatically add the import statements required. I nearly fell off my chair with delight when I learned that. ;)

      Cheers
      Sarah

  2. A great suggestion came in via Google+. From Sergii Pylypenko is a recommendation to name two things in the sample code ‘foo’ and ‘bar’, as it’s become a tradition. Ben Buchanan agrees, noting that he has sometimes searched for a pattern with foo and bar to find a sample or tutorial!

  3. This approach sounds pretty good. For internal-facing documentation, you might try a variant: instead of creating new sample code, find an existing pretty-good chunk of code and clean it up into something exemplary. It’s not always an option–the code you want to use for illustration is likely thrown together with other junk. But when it works out, it’s pretty sweet.

  4. Great article. I’m glad to see that you’re giving this topic the attention it deserves. One question. When you want more room to explain things than you can feasibly do in a code comment, how to you integrate that longer explanation with the code? Do you follow the code with your explanation? Do you precede the code with the explanation?

    In some code samples, I’ll briefly describe what the code does in one paragraph, present the code sample in its entirety (which includes brief comments in the code), and then follow the code with a section called “Code explanation,” where I step the reader through the code is more detail. It seems a bit clunky but I haven’t seen a better solution for it.

    • Hallo Tom
      That’s a good question. I think there isn’t a single solution for all cases. Often it will be overkill to step through the code in detail, especially if the code is illustrating the simplest use case. I like the style of giving a (textual) summary of what the code must do, then adding the code sample which includes the comments in the code. This sets up a framework in the reader’s mind, and then gives the details to fill that framework. There’s an example in the simple code sample already referenced. If necessary, we can them discuss specific bits that are complex or super-important.
      Cheers
      Sarah

  1. Pingback: Tips for writing code comments in developer documentation | I'd Rather Be Writing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,447 other followers

%d bloggers like this: