Showing posts with label code conventions. Show all posts
Showing posts with label code conventions. Show all posts

Thursday, November 20, 2008

XML Documentation (continued)

Wow! I got sidetracked on getting out some other posts and, well... life, and I just realized I never continued the articles I started about XML documentation! For my earlier posts about code documentation, see Documentation is the Key and XML Documentation. So, as promised, here's how I use XML comments to document methods and events.

Methods
Documenting methods can get a little more complicated. Like all other comment blocks, I always include a <summary></summary> tag that gives a brief description of the method. If the method contains parameters, I'll follow the summary with a <param> tag for each parameter passed. If the method returns a value, I'll follow the parameter tags with a <returns></returns> tag that describes the return value. If the method throws any exceptions, those get documented within <exception></exception> tags. Finally, if the method needs further explanation, I'll include a <remarks></remarks> tag and possibly an example in an <example></example> tag.

In addition to the above tags, method documentation might also include <see></see> tags to refer to related properties, methods, or classes. If I need to refer to a parameter by name within the documentation (outside of that parameter's <param> tag), I'll surround it with a <paramref></paramref> tag. If any parameter type is an enumeration, I may also include a <list></list> with enumeration values and their meaning within the context of the method.

Method comments can get rather complex, so here's an example:

''' <summary>
''' Saves the document to a file.
''' </summary>
''' <param cref="filename">
''' The name of the file to which the document will be saved.
''' <param>
''' <param cref="format">
''' The format in which to save the document. Can be any of
''' the following values:
''' <list>
''' <li>
''' XML
''' <description>
''' Document text and formatting saved using XML schema.
''' </description>
''' </li>
''' <li>
''' Binary
''' <description>
''' Document saved as binary data.
''' </description>
''' </li>
''' <li>
''' RTF
''' <description>
''' Document saved in rich-text format.
''' </description>
''' </li>
''' </list>
''' <param cref="overwrite">
''' If <b>True</b> and this file already exists, it will be overwritten
''' without warning. If <b>False</b> and this file already exists, this
''' function will not save the file and will exit with a return value of
''' <b>False</b>.
''' <returns>
''' <b>True</b> if the document was saved with no errors; otherwise,
''' <b>False</b>.
''' </returns>
''' <exceptions cref="ArgumentNullException">
''' Occurs if the filename is null (<b>Nothing</b> in Visual Basic).
''' </exception>
''' <exception cref="IOException">
''' Occurs if an error occurred attempting to write the file.
''' </exception>
''' <remarks>
''' <seealso cref="Load"></seealso>
''' </remarks>
Public Function Save(ByRef filename As String, ByRef format As FileFormatEnum, _
ByRef overwrite As Boolean) As Boolean
...
End Function


Events
Events are pretty straightforward. I usually don't do more than include a <summary> tag and possibly a <remarks> tag.

Example:

''' <summary>
''' Occurs when the document is being the completion status of the
''' progress has changed.
''' </summary>
''' <remarks>
''' The <see cref="ProgressUpdatedEventArgs></see> event argument
''' passed with the event contains an integer property,
''' <see cref="Progress"></see>, that contains the current completion
''' status, represented as a percentage.
''' </remarks>
Public Event ProgressUpdated as EventHandler(Of ProgressUpdatedEventArgs)


More Info
For a complete list of XML tags suggested by Microsoft, see Recommended Tags for Documentation Comments (C#).

Sunday, August 24, 2008

XML Documentation

OK, that last post ended up as being a bit of a tease, so I'll jump right into things today. I write most of my comments using XML. Before the days of XML, I used to write "header comments" for all my major code blocks. Each of these header sections would contain a number of pre-defined elements. With the advent of XML and the inclusion of support for XML-style comments in Visual Studio, it became easy to create consistent, thorough documentation for each primary element of my code (by "primary element" I mean classes, properties, methods, and events).

Using XML comments in .NET code has several advantages.

  • XML's well-defined tags and the assistance of auto-complete make it easy to create consistent comment blocks.
  • Starting with Visual Studio 2005, XML Documentation Comments can be extracted from VB, C#, and C++ source code files. When you compile with the /doc parameter, the compiler will extract all XML tags from your source code and create an XML documentation file. You can instruct the compiler to extract these comments into an XML file. These comments can be used by NDoc and SandCastle to create HTML and chm help files.
  • Finally, these XML files can also be used to add IntelliSense in VisualStudio to your own classes.

  • I try to comment every class, method, property, and event. In order for the compiler to extract documentation, the code comments need to meet the following two conditions:

  • The comment must begin with ''' in VB files and /// in C# or C++ files.
  • The documentation to be extracted must be encased within XML tags.

  • While the compiler will accept any valid XML tags, I generally use a specific set of tags for each element that I'm commenting. In the remainder of this post I'll describe how I comment classes and properties. I'll finish my discussion of XML comments in the next post where I describe how I comment methods and events.

    Classes
    At the very minimum, I use the <summary> tag to provide a short summary of the class. This summary describes what the class is and its use. A more detailed description goes in the <remarks> tag. Other tags I may use in a class comments block are <example> (usually used with the <code> tag), and <seealso> to add a See Also section to the documentation containing links to related classes. Finally, I add the non-standard tag <author> to all my class comment blocks.

    Here's an example:

    ''' <summary>
    ''' A simple class that represents a US mailing address.
    ''' </summary>
    ''' Keven Lehmann
    ''' <remarks>
    ''' <para>
    ''' This class contains properties for all of the elements in a common US
    ''' mailing address. It provides basic validation for state abbreviations
    ''' and ZIP code formats (basic and ZIP+4) but does not verify that the
    ''' address represents an actual US mailing address.
    ''' </para>
    ''' <para>
    ''' The following example demonstrates a typical use for this class:
    ''' </para>
    ''' <example>
    ''' <code>
    ''' Public Function GetSampleAddress() as String
    ''' Dim addr as USAddress = new USAddress()
    ''' addr.Recipient = "Keven Lehmann"
    ''' addr.Street = "101 Main St"
    ''' addr.City = "Somewhere"
    ''' addr.State = "MD"
    ''' addr.ZIP = "21212-1212"
    ''' Return addr.ToUspsString()
    ''' End Function
    ''' </code>
    ''' </example>
    ''' </remarks>
    Public Class USAddress
    ...
    End Class


    Properties
    For properties, I always include the <summary> and <value> tags, although <value> often turns out to be a rehashing of the <summary>. If I feel there is anything about the property that needs extra clarification, I'll include that in a <remarks> tag. Other common tags I may use with a property are <example> for examples of use and <see> to refer to related functions from within the body of the documentation.

    Here is an example:

    ''' <summary>
    ''' Gets the <see cref="Person"></see>'s full name.
    ''' </summary>
    ''' <value>
    ''' The full name of the <b>Person</b>, comprising their
    ''' <see cref="FirstName"></see> and <see cref="LastName"></see>,
    ''' separated by a space.
    ''' </value>
    Public ReadOnly Property FullName() As String
    ...
    End Property


    That's it for right now. Next time I'll finish up XML comments by covering Method and Event comments.

    Sunday, August 17, 2008

    Documentation is the Key

    Documentation is one of the most important, yet overlooked, aspects of programming. No one programs in a vacuum. At some point, someone else will look at your code and have to understand it. For that matter, at some point in the future you may have to look at your code and understand it! When the code is fresh in your mind, understanding it is easy. But how easy is it to follow six months from now? One year? Two years? By that time, several projects have come and gone and that code is stale and musty in your mind. Do you really want to laboriously read through it line-by-line just to understand how it works again? Wouldn't it be easier if you could skim through your code and quickly home in on the piece you need to fix or change?

    Clearly-written code can certainly help you achieve that objective, but I feel that clearly-documented code can make the task even easier. With well-documented code you can read through the documentation rather than the code itself to understand what each piece of code is supposed to do. And well-written documentation in plain English (or French or German or whatever your native language is) is always much easier to understand than the actual code itself (and if it isn't, then you really need to work on your writing skills).

    If you're tasked with making changes to a project that you've never been involved with before and the previous developers didn't properly document their work, you may quickly feel the urge to track down those programmers and do bodily harm (if so, hopefully they were consultants who were long gone and not your co-workers). No documentation means having to slog through thousands of lines of code (or more) to track down the code you need. Sometimes you have to wade through all of the code just to get a basic understanding of the application before you can even dream of modifying it. Don't be one of those programmers that other programmers will one day want to kill!

    On the other hand, good documentation means having external documents that help you see the overall structure of the application -- the big picture. From that, you can see which pieces of the code (layers, namespaces, or classes) are important to your current task. More detailed documentation about those code sections (both external documents as well as class-level comments) can help you drill-down to even smaller pieces of the code. Finally, documentation on the class properties and methods as well as inline comments can help you pinpoint the exact sections of your code that you need.

    Good documentation involves several things. The main aspects of well-documented code are internal documentation, self-documenting code, and external documentation.

    Internal Documentation
    Actively documenting the body of your code is perhaps the biggest topic of the three types of documentation I mentioned. Thus, I'll start with that and spend most of my time talking about it. Internal documentation itself can be broken down into several topics: class-level comments; method-, property-, and event-level comments; and inline (or code block) comments. In addition, there are a couple side-topics I'd like to discuss: XML documentation and code regions.

    It is vitally important to rigorously comment your code. Unfortunately, writing comments tends to be boring compared to the challenge of coding and is often neglected. It can also be time-consuming and thus easy to skip when you're working under a tight deadline. I know I'm still far from perfect when it comes to properly documenting my code, but I'm aware of its importance and since I constantly strive to improve the quality of my code, I also constantly strive to improve the quality of my code comments (which I feel has a net effect of improving the quality of the code itself).

    The next few sections delve into each aspect of internal documentation in more detail. At the end, I'll provide a few tips and tricks I've discovered that help make it easier to include and maintain good documentation. Some of them even make you a more efficient programmer, so you have even less excuses for not including good comments in your code!

    OK, I'm long-winded, I'll admit it. so without further adieu, let's start commenting about comments... next time. ;-)

    full window
    full window
    full window
    full window

    Monday, June 30, 2008

    Code Conventions

    And no, by code "conventions" I'm not talking about JavaOne or VSLive!

    Code conventions are the standards you live by (or are forced by your employer to live by) that nitpick define how your code should look. Code conventions commonly specify things like how you name your variables, functions, and classes; guidelines for how to organize the text of your code on-screen; and requirements for properly documented code. If you haven't had to comply with code conventions (and maybe even if you have), you may wonder why anyone would want or need such stifling-sounding constriants. The easiest way to answer that question is with another question: have you ever had to look at someone else's code and try to understand it?

    I'm assuming almost everyone answered yes to that question. If you've ever had a hard time trying to figure out just what was going through the head of the person who wrote that code you've been staring at, you know why we need code conventions (unless it was actually a bad piece of code, not just badly written... there's plenty of that out there too, but that's another topic entirely). Code conventions help make it easier for others to read and understand your code. Or to put it more selfishly: code conventions make it easier for you to understand someone else's code!

    Now are you ready to accept that code conventions just might be a good thing?

    The main problem with this idea is the question "who makes the standards?" There are some common, wide-spread conventions out there... some good, some not-so-good (Hungarian notation, anyone?). Most likely, the standards you follow will be the ones set down by your employer... hopefully they're making you follow some good ones! Without any universal standards -- and the firepower to force everyone to follow them -- you'll still undoubtedly run into lots of marginally intelligible code, but if your company enforces any sort of code conventions at least you'll be able to read your coworker's code fairly easily after he quits to form what he thinks will be the next MySpace.

    When I started at my current employer, there were no documented code conventions for VB development. We have a fairly small number of programmers so perhaps it was felt that there was no need for them, but all it takes is one sloppy programmer to make a big mess. Since some of our most complex systems have been written by multiple contractors, the code we have to maintain was all over the place, stylistically speaking. It didn't take me too long to realize that even a small team needs some guidelines on how their source code should be written. And since I was a lead programmer, I got to dictate what those guidelines would be!

    When I sat down to start writing my guidelines for coding conventions, I decided to focus on four main areas: documentation, code formatting, programming techniques, and source code organization. Each of these is a very large topic. Some of what I eventually developed came from my own experiences writing and maintaining code. A lot of the naming conventions I adopted come from Sun Microsystem's Java Code Conventions. Many of them I'm still developing as I go along.

    Over the next several posts I hope to share the highlights in each of these areas. And since I know it's impossible for me to have thought of everything, I'd love to see what anyone else has to say on this topic as well!

    full window