Use realistic code examples

Unrealistic code examples simply make your documentation harder to understand.

For instance, if you have to provide some string literals, the Foos and bars are really bad choices. If you have to show your reader how to use your code, why not to use a real-world example? A common practice is to make sure that each code example can be cut and pasted into a real program.

To show an example of bad usage, let's assume we want to show how to use the parse() function from the atomisator project, which aims to parse RSS feeds. Here is the usage example using an unrealistic imaginary source:

>>> from atomisator.parser import parse
>>> # Let's use it:
>>> stuff = parse('some-feed.xml')
>>> next(stuff)
{'title': 'foo', 'content': 'blabla'}  

A better example, such as the following, would be using a data source that looks like a valid URL to RSS feed and shows output that resembles the real article:

>>> from atomisator.parser import parse
>>> # Let's use it:
>>> my_feed = parse('http://tarekziade.wordpress.com/feed')
>>> next(my_feed)
{'title': 'eight tips to start with python', 'content': 'The first tip is..., ...'}

This slight difference might sound like overkill but, in fact, makes your documentation a lot more useful. A reader can copy those lines into a shell, understand that parse() expects a URL as a parameter, and that it returns an iterator that contains web articles.

Of course, giving a realistic example is not always possible or viable. This is especially true for very generic code. Even this book has a few occurrences of vague "foo" and "bar" strings. Anyway, you should always strive to reduce the amount of such unrealistic examples to a minimum.

Code examples should be directly reusable in real programs.