Improving Code Quality with Code Snippets

We mentioned in the previous section that Generate Method Stub refactoring is a labor-saving technique during coding, rather than a refactoring applied wholly after the fact. Another labor-saving technique that may be applied while writing code is code snippets.

The basic idea is to utilize a library of pre-built tried-and-tested code segments for performing common tasks. Need to parse an XML file but can't remember how? Or not sure how other developers in your team do it? Just find the relevant code snippet.

This idea of pre-built code segments is not unique to Visual Studio 2005 and has analogues, for example, in the IBM Rational XDE Code Templates feature. That feature is described as a mechanism for locking down implementations for reuse consistently across teams and projects — a description that fits perfectly with code snippets too.

Code snippets can be thought of as developer's equivalent to the architect's patterns. Using a combination of patterns (at the architectural level), code snippets (as you write the code), and refactoring (to rework the code), you can significantly improve the quality of your software development.

Using code snippets in Visual Basic

We'll demonstrate this feature using an XML parsing example. Suppose you'd like a general-purpose method that takes in a string containing XML data and displays each of the tagged elements within that string. The only problem is that you can't remember how to do it!

Well, someone else who knew how to do it has helpfully encoded that knowledge into a code snippet that you can reuse.

One way to use that snippet is to create a simple Visual Basic "Console" application project, right-click within the Main method, and choose Insert Snippet from the context menu. You should see a list of code snippet categories (see Figure 11-11) from which you can choose the XML category.

image from book
Figure 11-11

Having selected a category by double-clicking, you can then choose a specific snippet from within that category. Figure 11-12 shows the snippet Read XML from a String being chosen.

image from book
Figure 11-12

Notice in Figure 11-12 that a shortcut for this code snippet is indicated, with the name xmlreadstring. If you know the shortcut name for the code snippet you wish to include, you can simply type that shortcut name in the code editor and press the Tab key to expand the full code automatically. In this case, you would place the cursor at the required place within your code, type xmlreadstring, and press Tab.

Either way, the resultant code will be as follows:

     Module CodeSnippetsXML         Sub Main()         ' Create the reader.         Dim reader As XmlReader = XmlReader.Create(New StringReader("<book/>"))         While reader.Read()         End While         End Sub     End Module 

This code is entirely self-sufficient, and because it has been placed within the Main method of a Console application, it can be tested right away simply by running the project. Do that if you like, to confirm that it works.

Actually, that example is not too useful as it stands because the XML string is hard-coded within the example. Much more useful would be a separate method containing the XML processing code, with the XML string passed in as a parameter. That's where refactoring comes in handy.

Using a combination of the Extract Method and Promote Local Variable to Parameter refactorings, you can rework that code as follows:

     Module CodeSnippetsXML         Sub parseXML(ByVal xmlData As String)         ' Create the reader.         Dim reader As XmlReader = XmlReader.Create(New StringReader(xmlData))         While reader.Read()         End While         End Sub         Sub Main()         Dim xmlData As String         xmlData = _           "<book>" & _           "  <title>Book Title</title>" & _           "  <price>5.95</price>" & _           "</book>"         parseXML(xmlData)         End Sub     End Module 

The parsing of the XML is now encapsulated entirely within the parseXML subroutine, thus creating a reusable method. The setting up of the XML data string is retained within the Main method purely as an example, and that code could be reworked — for example, to read the XML data string from a file, perhaps using the "Read text from a File" code snippet!


For the record, we created that code listing by refactoring the code manually, because — as we pointed out — the automated refactoring of Visual Basic code is not supported by Visual Studio 2005. You could try using the Refactor! for Visual Basic 2005 add-in referenced earlier.

To make the parseXML method truly reusable, you might consider refactoring further to separate out the display statements — that is, MessageBox.Show — from the parsing code. Rather than display the elements from the XML string as they are encountered, you might collect these into an array that is returned by the parseXML method.

Using code snippets in Visual C#

The procedure for inserting snippets into Visual C# code is exactly the same as for Visual Basic. Just right-click in code and choose Insert Snippet from the context menu. Or, if you know the shortcode of the snippet, just type that shortcode and press Tab.

The first thing you'll notice is that the available snippets are not C# equivalents of the Visual Basic snippets, which admittedly seems rather inconsistent. The Visual C# snippets are mainly structural in nature and are typified by the foreach snippet that provides template code for a foreach statement. When expanded it looks like this:

      foreach (object var in collection_to_loop)      {      } 

Unless you routinely name your collections with the name collection_to_loop, that snippet will not be too useful as it stands. Visual Studio treats such variable names as replacement points that you can tab through and type whatever is appropriate for your code. In the case of the foreach snippet, you will be prompted initially to replace the object item, then (on pressing Tab) the var item, and then (on pressing Tab again) the collection_to_loop entry.

Some of the more interesting C# code snippets enable the insertion of entirely new methods, rather than code within existing methods. For example, the equals snippet inserts the following code, which shows how to override the default equality checking of objects:

     // override object.Equals     public override bool Equals (object obj)     {         //         // See the full list of guidelines at         //         //   en-us/cpgenref/html/cpconequals.asp         // and also the guidance for operator== at         //         //   en-us/cpgenref/html/cpconimplementingequalsoperator.asp         //         if (obj == null || GetType() != obj.GetType())         {         return false;         }         // TODO: write your implementation of Equals() here.         throw new Exception("The method or operation is not implemented.");         return base.Equals (obj);     } 

You might be interested to know that besides inserting code snippets using Insert Snippet, you can also insert some of these same snippets by highlighting a section of code, right-clicking, and choosing Surround With from the context menu. Try this out by surrounding a block of code with a do / while construct.

Code Snippets Manager

Whatever language you use, the Code Snippets Manager provides full control over the snippets library. It enables you to manage a set of project-related and inter-project code assets to encourage consistency across implementations.

Choosing Tools image from book Code Snippets Manager triggers the dialog shown in Figure 11-13. You can see that we have navigated the VB snippets library to find the "Read XML from a String" snippet demonstrated earlier.

image from book
Figure 11-13


You can change the language from the default Visual Basic in the pull-down list to navigate the available snippets for Visual C# and Visual J#.

Notice that the Code Snippet Manager indicates the location where each snippet is stored, in a file-and-folder structure on disk that corresponds exactly with the hierarchy you see when inserting a snippet. On your machine, the base location for those snippets will be something like C:\Program Files\ Microsoft Visual Studio 8\Vb\Snippets\1033\.

Each snippet is stored in its own XML file with the extension .snippet, such as the file ReadXMLFrom String.snippet listed below. Notice in particular the contents of the <Imports> tag, which despite its name is language agnostic but ensures that the correct Imports statements (VB) or using statements (C#) are included with the snippet. Also note the contents of the <Code> tag that contains the snippet code itself:

     <?xml version="1.0" encoding="UTF-8"?>     <CodeSnippets xmlns="">         <CodeSnippet Format="1.0.0">         <Header>           <Title>Read XML from a String</Title>           <Author>Microsoft Corporation</Author>           <Description>Reads XML data from a string.</Description>           <Shortcut>xmlReadString</Shortcut>         </Header>         <Snippet>           <References>             <Reference>               <Assembly>System.Xml.dll</Assembly>               <Url />             </Reference>           </References>           <Imports>             <Import>               <Namespace>System.IO</Namespace>             </Import>             <Import>               <Namespace>System.Xml</Namespace>             </Import>           </Imports>           <Declarations>             <Literal>               <ID>XmlString</ID>               <Type>String</Type>               <ToolTip>Replace with code to initialize string with XML.</ToolTip>               <Default>"&lt;book/>"</Default>             </Literal>           </Declarations>           <Code Language="VB" Kind="method body"><[CDATA[' Create the reader.     Dim reader As XmlReader = XmlReader.Create(New StringReader($xmlString$))     While reader.Read()     End While]]></Code>         </Snippet>         </CodeSnippet>     </CodeSnippets> 

If you refer back to Figure 11-13, you will notice additional buttons that enable you to import additional snippets and even search for new ones on the web.

If you're comfortable with the XML syntax in the previous listing, then you can even author your own snippets; and if you're not, and you're a VB programmer, then help is at hand in the form of the separate Code Snippet Editor for Visual Basic 2005, which is available for download at

Professional Visual Studio 2005 Team System
Professional Visual Studio 2005 Team System (Programmer to Programmer)
ISBN: 0764584367
EAN: 2147483647
Year: N/A
Pages: 220 © 2008-2017.
If you may any questions please contact us: