Code examples illustrate how to use a programming element to implement specific functionality. They might include:
- Simple, one-line examples interspersed with text.
- Short, self-contained examples that illustrate specific points.
- Long samples that illustrate multiple features, complex scenarios, or best practices.
Developers use code examples to:
- Assess a technology through its API during planning.
- Learn or explore a language or technology.
- Write and debug code.
Many developers copy example code from documentation into their own code or adapt code examples to their own needs.
To create useful code examples, identify tasks and scenarios that are meaningful for your audience, and then create examples that illustrate those scenarios. Code examples that demonstrate product features are useful only when they address the problems that developers are trying to solve.
Guidelines for planning code examples
Create concise examples that exemplify key development tasks. Start with simple examples and build up complexity after you cover common scenarios.
Prioritize frequently used elements and elements that may be difficult to understand or tricky to use.
Don't use code examples to illustrate obvious points or contrived scenarios.
Create code examples that are easy to scan and understand. Reserve complicated examples for tutorials and walkthroughs, where you can provide a step-by-step explanation of how the example works.
Add an introduction to describe the scenario and explain anything that might not be clear from the code. List the requirements and dependencies for using or running the example.
Provide an easy way for developers to copy and run the code. If the code example demonstrates interactive and animated features, consider providing a way for the developer to run the example directly from your content page.
Use appropriate keywords, linking strategies, and other search engine optimization (SEO) techniques to improve the visibility and usability of the code examples. For example, add links to relevant code example pages and content pages to improve SEO across your content. See Search and writing.
Guidelines for writing code examples
Design code for reuse. Help developers determine what to modify. Add comments to explain details, but don't overdo it. Don't state the obvious.
Show expected output, either in a separate section after the code example or by using code comments within the code example.
Consider accessibility requirements for code that creates UI. For example, include alternate text for images.
Write secure code. For example, always validate user input, never hard-code passwords in code, and use code-analysis tools to detect security issues.
Show exception handling only when it's intrinsic to the example. Don't catch exceptions thrown when invalid arguments are passed to parameters.
Always compile and test your code.
Submit and view feedback for