Creating Good Sample Code
Creating Good Sample Code

Creating Good Sample Code

Trying to describe code with text is like trying to explain an Italian poem in English. - Google
Table of Contents

Introduction

Good sample code is often the best documentation.
Good samples are correct and concise code that your readers can quickly understand and easily reuse with minimal side effects.
The following documentation summarises the essentials of correct and concise sample code.

Correct

Sample Code Criteria
  • Errors: Build without errors.
  • Task: Do what it claims it can do.
  • Be Production ready: e.g. should contain no security vulnerabilities.
  • Language conventions: Follow language-specific conventions.
  • Best practices: Influence your users to follow best practices.
  • Extensively tested and regularly maintained.
Sample Programs- Key Notes
A more complete and functional program compared to sample code/snippet-usually smaller demonstrating just a specific concept.
  • Unit tests: Minimize use of unit tests as sample program.
  • Avoid snippet-heavy documentation as it degrades over time. Teams tend test sample programs more rigorously over snippets.
 

Running Sample Code

Good documents explain how to run sample code including pre-requisite activities needed to run the samples.
Writers should also consider doing the following:
  • Include option to run the code directly in the documentation as users may not perform preceding activities properly.
  • Include expected output of running sample code.

Concise

Keep sample code short, including essential components while avoiding bad practices-Correctness over conciseness.
Example - By Google
When a novice C programmer wants to learn how to call the malloc function, give that programmer a brief snippet, not the entire Linux source tree. 

Understandable

Recommendations include:
  • Descriptive names: Use descriptive variable, class or method names.
  • Avoid confusion: Difficult programming tricks may confuse readers.
  • Avoid Nesting: Deeply nested code can be both ugly and confusing
  • Optional: Judiciously use coloured or bold fonts to direct the reader’s attention.
Exercise
Which of the following would be a more helpful line of code in a sample program? Assume that the target audience consists of software engineers new to the go.so API.
  1. MyLevel = go.so.Level(5, 28, 48)
  1. MyLevel = go.so.Level(rank=5, 28, 48)
  1. MyLevel = go.so.Level(rank=5, dimension=28, opacity=48)
My Answer
  1. MyLevel = go.so.Level(rank=5, dimension=28, opacity=48)
It’s more descriptive and ensures I don’t have to guess what each parameter is.
Google’s Answer
Answer 3 is the best choice here. Although it is tempting to keep sample code as short as possible, omitting parameter names makes it harder for novices to learn.

Commented

Recommendations include:
  • Clarity/Brevity: Try to keep comments short without sacrificing clarity.
  • Stating The obvious: Avoid comments about obvious code, but be conscious that what’s obvious to you, the expert may not be obvious to the beginner.
  • Comment non-intuitive code: Focus on commenting non-intuitive code.
  • Experienced readers need understanding: They need to not just know what the code is doing but why the code is doing it.
Lastly, Try to put essential short descriptions as comments within the code and lengthy descriptions as text before sample code/program.
Note: If you must sacrifice production readiness in order to make the code shorter and easier to understand, explain your decisions in the comments.
Exercise - By Google.
What problems do you see in the comments within the following snippet? Assume that the code is aimed at programmers who are new to the br API but who have some experience with the concept of streams:
/* Create a stream from the text file at pathname /tmp/myfile. */ mystream = br.openstream(pathname="/tmp/myfile", mode="z")
Answer by Google
The comments contain the following flaws:
  • The comment elaborates on a fairly obvious part of the code.
  • The snippet doesn't explain the non-obvious portion of the code. Namely, what is the mode parameter and what does a value of z mean?
My attempt
The comment states the obvious about the pathname. It’s clearly indicated in the code.
 

Reusable

Recommendations include:
  • Provide all info necessary to run sample code.
  • Provide extensible/customizable code.
Sample code should be efficient, compilable and concise.

X and O Example

It’s wise to show readers what’s good and what’s bad when giving an example.
Example - By Google
For example, many programming languages permit programmers to place white space on either side of the equals sign. Now suppose that you were writing a tutorial on a language (such as bash) that does not permit white space on either side of the equals sign. In this case, showing both a good example and an anti-example will benefit the reader. For example:
# A valid string assignment. s="The rain in Maine."
# An invalid string assignment because of the white space on either side of the # equals sign. s = "The rain in Maine."

Sequenced

Good engineers want to go from simple to complex when learning certain technologies.
Exercise - By Google
Which of the following would be a good set of sample functions to support a tutorial introducing newcomers to the concept of functions?
  1. The following set of functions:
    1. A function that takes no parameters and doesn't return anything.
    2. A function that takes one parameter but doesn't return anything.
    3. A function that takes one parameter and returns one value.
    4. A function that takes three parameters and returns one value.
  1. The following set of functions:
    1. A function that takes three parameters and returns one value.
  1. The following set of functions:
    1. A function that takes one parameter and returns one value.
    2. A function that takes three parameters and returns one value.
Answer - By Google
The best answer is 1. Providing samples that cover a range of complexity is usually the wisest choice—particularly for newcomers. Resist the temptation to rush towards very complex sample programs, bypassing the beginner and intermediate sample programs that newcomers crave.
My Attempt
Option 1. It clearly goes into detail about the concept of functions. This ensures that readers would understand what happens when 0 or more parameters are used, as well as the expected return values.
 
Â