TYPOGRAPHIC CODE ELEMENTS

A few typographic code elements can make a program’s structure a bit easier to understand. They do not execute programming commands themselves, but they are an important part of how you can structure your code. These elements include comments, line continuation and joining characters, and line labels.

Comments

Comments can help other developers (or you at a later date) understand the program’s purpose, structure, and method. You start a comment by typing a single quotation mark (') that is not inside a quoted string. All of the characters starting at the quote and continuing until the end of the line are part of the comment and are ignored by Visual Basic.

If a line with a comment ends with a line continuation character (described shortly), Visual Basic ignores that character. That means the line is not continued onto the next line, so the comment ends with the current line. In other words, you cannot use line continuation characters to make a multi-line comment.

To quickly comment or uncomment a large block of code, click and drag to select the code using the mouse and then open the Edit menu’s Advanced submenu. Select the Comment Selection command to comment out the selection or select Uncomment Selection to remove the comment characters from the front of the selection. Those commands are also available more conveniently as buttons in the Standard toolbar. Use the View menu’s Toolbars submenu to show or hide this toolbar.

Another way to quickly remove a chunk of code from the program is to surround it with compiler directives, as in the following code:

#If False Then
    Dim A As Integer
    Dim B As Integer
    Dim C As Integer
#End if

Use comments to make your code clear. Comments do not slow down the executable program (some superstitious developers think they must slow the code because they make the file bigger), so there’s no good reason to avoid them.

XML Comments

A normal comment is just a piece of text that gives information to a developer trying to read your code. XML comments let you add some context to a comment. For example, you can mark a comment as a summary describing a subroutine.

Visual Studio automatically extracts XML comments to build an XML file describing the project. This file displays the hierarchical shape of the project, showing comments for the project’s modules, namespaces, classes, and other elements.

The result is not particularly easy to read, but you can use it to automatically generate more useful documentation such as reports or web pages.

You can place a block of XML comments before code elements that are not contained in methods. Generally, you use them to describe a module, class, variable, property, method, or event.

To begin a comment block, place the cursor on the line before the element you want to describe and type three single quotes ('''). Visual Studio automatically inserts a template for an appropriate XML comment block. If the element that follows takes parameters, it includes sections describing the parameters, so it is in your best interest to completely define the parameters before you create the XML comment block. Otherwise you’ll need to add the appropriate comment sections by hand later.

The following code shows the XML comment block created for a simple subroutine. It includes a summary area to describe the subroutine, two param sections to describe the subroutine’s parameters, and a remarks section to provide additional detail.

''' <summary>
'''
''' </summary>
''' <param name="jobs"></param>
''' <param name="employees"></param>
''' <remarks></remarks>
Public Sub AssignJobs(ByVal jobs() As Job, ByVal employees() As Employee)
 
End Sub

Note that XML elements can span multiple lines, as the summary element does in this example.

You can add more XML comment sections to the block simply by typing them, following the convention that they should begin with three single quotes. For example, the following code adds some content for the comments in the previous code and an extra WrittenBy element that contains a date attribute:

''' <summary>
''' Assigns jobs to employees, maximizing the total value of jobs assigned.
''' </summary>
''' <param name="jobs">The array of Jobs to assign.</param>
''' <param name="employees">The array of Employees to assign.</param>
''' <remarks>The full assignment is not guaranteed to be unique.</remarks>
''' <WrittenBy date="4/1/12">Rod Stephens</WrittenBy>
Public Sub AssignJobs(ByVal jobs() As Job, ByVal employees() As Employee)
 
End Sub

COMMENT CONVENTIONS
Note that I just made up the WrittenBy element and its date attribute — they’re not part of some XML comment standard. You can put anything you want in there, although the comments will be easiest to use if you use standard elements such as param and remarks whenever possible.
These XML comments are somewhat bulky and hard to read. In the previous example, it isn’t easy to pick out the subroutine’s most important summary information with a quick glance at the code. To make reading XML comments easier, Visual Basic defines an outlining section for each XML comment block. If you click the minus sign to the left of the first line in the block, the whole block collapses and shows only the summary information. If you then click the plus sign to the left of the summary, Visual Studio expands the comments to show them all.

The following code shows the beginning of an application that assigns jobs to employees. The project contains two files, a form named Form1.vb and a code module named JobStuff.vb. The form contains very little code. The code module defines the Job and Employee classes and the AssignJobs subroutine. Each of these has an XML comment block.

Public Class Form1
    Private Jobs() As Job
    Private Employees() As Employee
End Class
 
Module JobStuff
    Public Class Job
        Public JobNumber As Integer
        ''' <summary>
        ''' A list of skills required to perform this job.
        ''' </summary>
        ''' <remarks>Represent required equipment as skills.</remarks>
        Public SkillsRequired As New Collection
        ''' <summary>
        ''' The value of this job.
        ''' </summary>
        ''' <remarks>Higher numbers indicate more priority.</remarks>
         Public Priority As Integer
    End Class
 
Public Class Employee
    Public FirstName As String
    Public LastName As String
    ''' <summary>
    ''' A list of skills this employee has.
    ''' </summary>
    ''' <remarks>Represent special equipment as skills.</remarks>
    Public Skills As New Collection
    End Class
 
    ''' <summary>
    ''' Assigns jobs to employees.
    ''' </summary>
    ''' <param name="jobs">Array of Jobs to assign.</param>
    ''' <param name="employees">Array of Employees to assign jobs.</param>
    ''' <remarks>Maximizes total value of jobs assigned.</remarks>
    ''' <WrittenBy date="7/26/04">Rod Stephens</WrittenBy>
    Public Sub AssignJobs(ByVal jobs() As Job, ByVal employees() As Employee)
 
    End Sub
End Module

In addition to providing documentation for your use, XML comments let IntelliSense provide additional information about your code. Figure 13-6 shows IntelliSense displaying information about the AssignJobs subroutine. It gets the description of the subroutine (Assigns jobs to employees) and the description of the jobs parameter (Array of jobs to assign) from the subroutine’s XML comments.

FIGURE 13-6: IntelliSense uses XML comments to display information about a subroutine and its parameters.

image

When you compile the application, Visual Studio extracts the XML comments and places them in an XML file with the same name as the executable file in the project’s binDebug directory. The result isn’t very readable but you can use it to generate more palatable documentation. Some third-party tools such as doxygen (http://www.doxygen.org) can also extract XML comments and build documentation.

Example program AssignJobs, which is available for download on the book’s website, defines job assignment classes that you can view with the Object Browser. If you compile the program (which actually doesn’t do any job assignment, it just defines the classes), you can examine its XML documentation.

Line Continuation

Line continuation characters let you break long lines across multiple shorter lines so that they are easier to read. To continue a line, end it with a space followed by an underscore (_). Visual Basic treats the following code as if it were all on one long line:

Dim background_color As Color = _
    Color.FromName( _
        My.Resources.ResourceManager.GetString( _
            "MainFormBackgroundColor"))

As the earlier section about comments explains, you cannot continue comments. A comment includes any space and underscore at the end of its line so the comment does not apply to the following line.

You can break a line just about anywhere that a space is allowed and between program elements. For example, you can break a line after the opening parenthesis in a parameter list, as shown in the following code:

AReallyReallyLongSubroutineNameThatTakesFiveParameters( _
    parameter1, parameter2, parameter3, parameter4, parameter5)

You cannot break a line inside a quoted string. If you want to break a string, end the string and concatenate it with the rest of the string on the next line, as in the following example:

Dim txt As String = "To break a long string across multiple lines, " & _
    "end the string and concatenate it with the rest of " & _
    "the string on the next line."

Visual Basic does not enforce its usual indentation rules on continued lines, so you can indent the lines in any way you like to make the code’s structure more clear. For example, many programmers align parameters in long subroutine calls like this:

DoSomething( _
    parameter1, _
    parameter2, _
    parameter3)

Implicit Line Continuation

Visual Basic can also guess where you are continuing a line even if you don’t use the line continuation character, at least sometimes. For example, Visual Basic can figure out that the statement shown in the following code isn’t complete until the final line so it treats all of this code as if it were written on a single long line:

Dim background_color As Color =
    Color.FromName(
        My.Resources.ResourceManager.GetString(
            "MainFormBackgroundColor"
        )
    )

Visual Basic does not allow implicit line continuation in all cases, however. For example, in the following code the Next i statement is split across two lines. Because a Next statement’s variable name is optional, Visual Basic doesn’t know that the following i is required so it doesn’t look for it.

For i As Integer = 1 To 10
 
Next
    i

In fact, the only place you can break the statement For i As Integer = 1 To 10 without a line continuation character and without confusing Visual Basic is after the equals sign. That’s a pretty confusing place to break the code anyway so I would recommend against it.

Some places that Visual Basic does allow implicit line continuation include:

  • After an equals sign
  • After a binary operator such as + or *
  • After commas
  • After opening parentheses or brackets and before closing parentheses or brackets

The following code shows a few examples:

<
    ComClass()
>
Public Class Employee
    Public Function CalculateStuff(
        ByRef v1 As Integer,
        ByRef v2 As Integer
    )
 
        Dim a As Integer =
            Math.Max(
                v1,
                v2 +
                12
            )
        Return a
    End Function
 
     ... 
End Class

Line Joining

Not only can you break a long statement across multiple lines, but you can also join short statements on a single line. To use two statements on a single line, separate them with a colon (:). The following line of code contains three statements that store the red, green, and blue components of a form’s background color in the variables r, g, and b, respectively:

r = BackColor.R : g = BackColor.G : b = BackColor.B

Line joining is most useful when you have many lines in a row that all have a very similar structure. By scanning down the lines, you can tell if there are differences that may indicate a bug.

Use line joining with some caution. If the statements are long, or if you have a series of joined lines with dissimilar structure, combining lots of statements on a single line can make the code harder to read. If the code is easier to read with each statement on a separate line, write the code that way. Using more lines doesn’t cost extra or make the code run any slower.

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

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