Code examples

Code examples illustrate how to use a programming element to implement specific functionality. They may include simple, one-line examples interspersed with text; short, self-contained examples that demonstrate specific points; and lengthy samples that illustrate multiple features, complex scenarios, or best practices.

Code examples are used by developers in all aspects of their work: during planning (to assess a technology through its API), when learning or exploring a language or technology, and when writing and debugging code. Developers often copy the examples that they find in the documentation to their own code, or adapt them to their own needs.

To create useful code examples, first identify the tasks and scenarios that are meaningful for your audience, and then create examples that illustrate those scenarios. Code examples that demonstrate product features are not useful unless they explicitly address the problems developers are trying to solve.

General guidelines

  • Create concise examples that exemplify key development tasks. Start with simple examples and build up complexity after you cover common scenarios.

  • If you can’t provide examples for all programming elements, focus on frequently used elements and elements that may be difficult to understand or tricky to use.

  • Don’t create code examples that are too complex to scan or understand easily. Reserve complicated examples for tutorials and walkthroughs, where you can provide a step-by-step explanation of how the example works.

  • Don’t use code examples to illustrate points that are obvious or scenarios that are contrived.

  • Add an introduction to describe the scenario that the code example illustrates and to explain anything that might not be clear from the code. List the requirements and dependencies for using or running the example.

  • Design your code for reuse by making it easy for users to determine what to modify. Add comments to explain details, but don’t over-comment. 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.

  • For code that creates UI, consider accessibility requirements. For example, include alternate text for images.

  • Write secure code. For example, always validate user input, never hardcode passwords in code, and use code analysis tools to detect security issues.

  • Show exception handling only when it is intrinsic to the example. Do not catch exceptions that are thrown when invalid arguments are passed to parameters.

  • If you’re publishing your content on the web, provide an easy way for users to copy and run the code. If the code example demonstrates interactive and animated features, consider providing a way for the user to run the example directly from your content page.

  • If you’re publishing your content on the web, use the appropriate keywords, linking strategies, and other search engine optimization (SEO) techniques to improve the visibility and usability of the code example. For example, add links to relevant code example pages and content pages to improve SEO across your content.

For more information, see Help customers find your content (Chapter 2).

Code formatting and naming guidelines

  • Use white space and indentation to improve the readability of your code. The Microsoft convention is to use four spaces per indent level for most programming languages, and two spaces per indent level for markup languages (HTML and XML).

  • Use blank lines to separate individual tasks or components in the code.

  • Avoid long lines of code; if possible, break these into multiple lines to improve readability.

  • Use a monospace font for all code examples, whether they’re embedded in text or displayed as separate paragraphs.

  • If you omit part of the example for clarity or length considerations, insert a comment at the point of omission to explain what should be added to make the code compile, or use an ellipsis (in a comment) to indicate that code segments have been omitted. Identify code that users must edit or add before the code can be compiled. If your documentation will be localized, consider putting this information in the body of the topic as well.

  • Observe the casing and coding conventions for the technology or language that you are documenting. For HTML, follow XHTML guidelines.

  • Use fictitious people names, company names, email addresses, and URLs.

  • Remember worldwide users. Do not use examples that include U.S.-centric data, such as zip codes or sports teams.

  • Do not use sensitive geographic and cultural references.

  • Do not use offensive language or slang. For example, do not use foo or bar or their derivatives when naming coding constructs.

  • Use descriptive construct names. Do not use names that are too generic or that include the prefix My. For example, use the property name MessageString instead of MyProperty or Data.

Code commenting guidelines

  • Use descriptive phrases that explain what the code does.

  • Use the correct delimiter for the programming language that you are using. For example, use two forward slashes (//) followed by a space to denote a comment for C++, C#, and JScript code. Use an apostrophe (‘) followed by a space to denote a comment for Visual Basic code.

  • Place each comment on its own line and before the code that it’s describing. If you must use trailing comments (on the same line as the code), keep the comment short, especially if the comments will be localized.

  • If your comment is lengthy, consider including that information within the body of the topic instead.

  • For multiline comments, use the comment delimiter, such as two forward slashes (//), on each line. Do not use the /* …*/ convention, which could cause problems when users copy and paste portions of the code into their own applications.

  • Consider localization when you decide whether to include information in a comment or in the body of a topic. Comments are sometimes not localized because of cost considerations.

  • Use complete sentences whenever possible, and observe standard rules of punctuation and grammar.

  • Do not use first person. For example, do not say “Here we display a list of customers.” Use present tense for comments that describe a code block, and use imperative mood to describe the action within that code block. Also use imperative mood to provide instructions for using the code example, as follows.

    // Displays a list of customer information in the console. 
    public void PrintCustomers(List<Customer> customerList)
    {
        // Display the name for each customer.
        foreach (var customer in customerList)
        {
            Console.WriteLine("Name: {0}, {1}",
                customer.LastName, customer.FirstName);
        }
    }
    // Insert code for get and set accessors.
  • If you use comments to display the output of the code example, introduce the output with a comment such as “This code displays the following output.” If the output varies, say “This code displays output similar to the following” instead.

Referring to code examples

Use code example to refer to source code that is included in content to illustrate a development task. Code examples are usually code fragments but may also include complete examples that users can copy to their computers, compile, and run. Introduce a code example with a complete sentence that ends with a period, not a colon.

Use code sample to refer to source code files that users can download to their computers and use in their development projects. For example, the Samples Gallery on MSDN provides code samples that users can download and use in Visual Studio.

Do not use code snippet.

Additional resources for writing code

  • Cwalina, Krzysztof and Brad Abrams. Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries. 2nd ed. Addison-Wesley, 2008.

  • Howard, Michael and David LeBlanc. Writing Secure Code. 2nd ed. Redmond, WA: Microsoft Press, 2003.

  • McConnell, Steve. Code Complete. 2nd ed. Redmond, WA: Microsoft Press, 2004.

  • The Design guidelines for developing class libraries section of the MSDN Library describes the conventions and recommendations for developing .NET Framework classes and components.

  • The Visual Studio languages section of the MSDN Library provides programming information about Visual Basic, C#, C++, JScript, and F#.

  • The Program structure and code conventions (Visual Basic) section of the MSDN Library discusses program structure and code conventions in Visual Basic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.226.66