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 multiline comment.

In the following code, the first declaration is followed by a comment. The comment ends with a line continuation character so you might expect the second declaration to be part of the comment. That is not the case. Because this can be misleading, you should not end comments with a line continuation character. The second statement declares and initializes a string using a value that contains a single quote. Because the quote is inside a quoted string, it becomes part of the string and does not start a comment. The next single quotation mark outside of the string begins a new comment.

  Dim num_customers As Integer    ' The number of customers in the application. _ Dim product_name As String = "Miracle Code Fixer"  ' The name of this program. 

If you want to continue a comment on the following line, you must use another comment character, as in the following example:

  ' Return True if the address is valid. This function checks the address's ' format to see that it makes sense. It also looks up the ZIP code and ' verifies that the city is valid for that ZIP code. It does not verify ' that the street and street number exist. Private Function IsAddressValid(ByVal address_text As String) As Boolean ... 

To quickly comment or uncomment a large block of code, select it 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 Text Editor toolbar. Use the View menu, Toolbars submenu’s Text Editor command 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 the executable program down, so there’s no good reason to exclude 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.

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 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.

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="7/24/04">Rod Stephens</WrittenBy> Public Sub AssignJobs(ByVal jobs() As Job, ByVal employees() As Employee) End Sub 

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 Module1.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 m_Jobs() As Job     Private m_Employees() As Employee End Class Module Module1     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>The assignment 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 

Figure 3-11 shows the Object Browser describing the Job class’s SkillsRequired property. The area on the lower right shows the property’s XML summary and remarks sections. This project’s name is AssignJobsProject and its root namespace is AssignJobsRoot, so the complete path to the Job class shown in the tree view on the left is AssignJobsProject (project), AssignJobsRoot (root namespace), Module1 (module), Job (class).

image from book
Figure 3-11: The Object Browser displays an item’s XML summary and remarks sections.

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 bin\Debug directory. The following text shows the result. If you look through the document carefully, you can pick out the XML comments.

  <?xml version="1.0"?> <doc> <assembly> <name> AssignJobsProject </name> </assembly> <members> <member name="P:AssignJobsRoot.My.Resources.Resources.ResourceManager">      <summary>   Returns the cached ResourceManager instance used by this class. </summary> </member><member name="P:AssignJobsRoot.My.Resources.Resources.Culture">      <summary>   Overrides the current thread's CurrentUICulture property for all   resource lookups using this strongly typed resource class. </summary> </member><member name="T:AssignJobsRoot.My.Resources.Resources">      <summary>   A strongly-typed resource class, for looking up localized strings, etc. </summary> </member><member name="F:AssignJobsRoot.Module1.Job.SkillsRequired">      <summary>  A list of skills required to perform this job.  </summary>      <remarks>Represent required equipment as skills.</remarks> </member><member name="F:AssignJobsRoot.Module1.Job.Priority">      <summary>  The value of this job.  </summary>      <remarks>Higher numbers indicate more priority.</remarks> </member><member name="F:AssignJobsRoot.Module1.Employee.Skills">      <summary>  A list of skills this employee has.  </summary>      <remarks>Represent special equipment as skills.</remarks> </member><member name="M:AssignJobsRoot.Module1.AssignJobs( AssignJobsRoot.Module1.Job[],AssignJobsRoot.Module1.Employee[])">      <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>The assignment maximizes total value of jobs assigned.</remarks>      <WrittenBy date="1/13/07">Rod Stephens</WrittenBy> </member> </members> </doc> 

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 line as if it were tacked on to the end of the first line:

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

As the previous section 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 restart it on the next line, as in the following example:

  Dim txt As String = "To break a long string across multiple lines, " & _     "end the string, add the line continuation character (space + underscore) " & _     "and restart 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.

  DoSomething( _     parameter1, _     parameter2, _     parameter3) 

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:

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

Line continuation 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 make the code run any slower.

Line Labels

You can place a label to the left of any line of code. The label can be either a name or a number, followed by a colon. The following code defines three labels. The first is named DeclareX and marks the declaration of the variable X. The second has value 10 and is located on a line containing a comment. The third label, named Done, labels a blank line.

  DeclareX:  Dim X As Single 10:        ' Do something here. Done: 

You label a line if you will later want to jump to that line. For example, the GoTo, On Error GoTo, and Resume statements can make code jump to a labeled line. These are less useful in Visual Basic .NET than they were in Visual Basic 6 and previous versions that didn’t have structured error handling (the Try Catch block), but they are still available.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net