Write Readable Code and Comments for Windows Forms Applications

In this second part of a five-part series that shows you how to code and test a Windows Forms application, you will learn (among other things) how to make sure your code and comments are clear and readable. This will simplify the debugging process and in general make code maintenance much easier. This article is excerpted from chapter 3 of Murach's Visual Basic 2008, written by Anne Boehm (Murach, 2008; ISBN: 1890774456).

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
July 09, 2009
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

How IntelliSense helps you enter the code for a form

In figure 3-2, you saw how IntelliSense displays a list of the available members for a class or an object. IntelliSense can also help you select a type for the variables you declare, which you’ll learn how to do in chapter 4. And it can help you use the correct syntax to call a procedure as shown in chapter 6 or to call a method as shown in chapter 11.

With Visual Basic 2008, IntelliSense has been improved to help you even more as you enter the basic code for an application. In particular, IntelliSense can help you enter statements and functions as well as the names of variables, objects, and classes. Figure 3-5 illustrates how this works.

The first example in this figure shows the list that IntelliSense displays when you start to enter a new line of code. Here, because I entered the letter d, the list includes only those items that start with that letter. As described earlier in this chapter, you can enter as many letters as you want, and Visual Studio will continue to filter the list so it contains only the items that begin with those letters. You can also scroll through the list to select an item, and you can press the Tab or Enter key to insert the item into your code.

Note that when you select a keyword that begins a statement, a description of the statement is displayed in a tool tip along with the syntax of the statement. That can help you enter the statement correctly. In addition, as you enter the statement, you’re prompted for any additional keywords that are required by the statement.

The second example in this figure shows the list that’s displayed as you enter the code for an If statement. You’ll learn more about this statement in chapter 5. For now, just notice that after I typed a space and the letter t following the If keyword, Visual Studio displayed a list of all the items that begin with the letter T. That made it easy to select the item I wanted, which in this case was the name of a control.

If you’ve used previous versions of Visual Basic, you’ll appreciate these expanded IntelliSense features. For example, it’s easy to forget the exact syntax of a statement or function, so the tool tip that’s displayed when you select a statement or function can help refresh your memory. Similarly, it’s easy to forget the names you’ve given to items such as controls and variables, so the list that’s displayed can help you locate the appropriate name. And that can help you avoid introducing errors into your code.

Although it’s not shown here, Visual Basic 2008 IntelliSense also lets you see the code that’s behind a list while the list is still displayed. To do that, you simply press the Ctrl key and the list becomes semi-transparent. This eliminates the frustration a lot of programmers felt when code was hidden by an IntelliSense list in previous versions of Visual Studio.

The list that’s displayed when you enter a letter at the beginning of a line of code

The list that’s displayed as you enter code within a statement

Description

  1. The IntelliSense that’s provided for Visual Basic 2008 lists keywords, functions, variables, objects, and classes as you type so you can enter them correctly.
  2. When you highlight an item in a list, a tool tip is displayed with information about the item. 
     
  3. If you need to see the code behind a list without closing the list, press the Ctrl key. Then, the list becomes semi-transparent.

Figure 3-5.   How IntelliSense helps you enter the code for a form

The event handlers for the Invoice Total form

Figure 3-6 presents the two event handlers for the Invoice Total form. The code that’s shaded in this example is the code that’s generated when you double-click the Calculate and Exit buttons in the Form Designer. You have to enter the rest of the code yourself.

I’ll describe this code briefly here so you have a general idea of how it works. If you’re new to programming, however, you may not understand the code completely until after you read the next two chapters.

The event handler for the Click event of the Calculate button calculates the discount percent, discount amount, and invoice total based on the subtotal entered by the user. Then, it displays those calculations in the appropriate text box controls. For example, if the user enters a subtotal of $1000, the discount percent will be 20%, the discount amount will be $200, and the invoice total will be $800.

In contrast, the event handler for the Click event of the Exit button contains just one statement that executes the Close method of the form. As a result, when the user clicks this button, the form is closed, and the application ends.

In addition to the code that’s generated when you double-click the Calculate and Exit buttons, Visual Studio generates other code that’s hidden in the Designer.vb file. When the application is run, this is the code that implements the form and controls that you designed in the Form Designer. Although you may want to look at this code to see how it works, you shouldn’t modify this code with the Code Editor as it may cause problems with the Form Designer.

When you enter Visual Basic code, you must be aware of the two coding rules summarized in this figure. First, you must separate the words in each statement by one or more spaces. Note, however, that you don’t have to use spaces to separate the words from operators, although Visual Basic adds spaces for you by default. Second, if you want to continue a statement, you do that by coding a space followed by a line-continuation character, which is an underscore (_). You can see an example of that in both of the procedure declarations in this figure.

The event handlers for the Invoice Total form

  Public Class frmInvoiceTotal

     Private Sub btnCalculate_Click(ByVal sender As System.Object, _
             ByVal e As System.EventArgs) Handles btnCalculate.Click

         Dim discountPercent As Decimal
         If txtSubtotal.Text >= 500 Then
             discountPercent = 0.2
         ElseIf txtSubtotal.Text >= 250 And txtSubtotal.Text < 500 Then 
             discountPercent = 0.15
         ElseIf txtSubtotal.Text >= 100 And txtSubtotal.Text < 250 Then
             discountPercent = 0.1
         Else
             discountPercent = 0
         End If

         Dim discountAmount As Decimal = txtSubtotal.Text * discountPercent
         Dim invoiceTotal As Decimal = txtSubtotal.Text - discountAmount

         txtDiscountPercent.Text = FormatPercent(discountPercent, 1)
         txtDiscountAmount.Text = FormatCurrency(discountAmount)
         txtTotal.Text = FormatCurrency(invoiceTotal)

         txtSubtotal.Select()

     End Sub

     Private Sub btnExit_Click(ByVal sender As System.Object, _
             ByVal e As System.EventArgs) Handles btnExit.Click
         Me.Close()
     End Sub

  End Class

Coding rules

  1. Use spaces to separate the words in each statement.
  2. To continue a statement to the next line, type a space followed by an underscore (the line-continuation character).

Description

  1. When you double-click the Calculate and Exit buttons in the Form Designer, it generates the shaded code shown above. Then, you can enter the rest of the code within the event handlers.
  2. The first event handler for the Invoice Total form is executed when the user clicks the Calculate button. This procedure calculates and displays the discount percent, discount amount, and total based on the subtotal entered by the user. 
     
  3. The second event handler for the Invoice Total form is executed when the user clicks the Exit button. This procedure closes the form, which ends the application.

 

Figure 3-6.   The event handlers for the Invoice Total form

How to code with a readable style

When you build an application, Visual Basic makes sure that your code follows all of its rules. If it doesn’t, Visual Basic reports syntax errors that you have to correct before you can continue.

Besides adhering to the coding rules, though, you should try to write your code so it’s easy to read, debug, and maintain. That’s important for you, but it’s even more important if someone else has to take over the maintenance of your code. You can create more readable code by following the four coding recommendations presented in figure 3-7. These recommendations are illustrated by the event handler in this figure.

The first coding recommendation is to use indentation and extra spaces to align related elements in your code. This is possible because you can use one or more spaces or tabs to separate the elements in a Visual Basic statement. In this example, all of the statements within the event handler are indented. In addition, the statements within each clause of the If statement are indented and aligned so you can easily identify the parts of this statement.

The second recommendation is to separate the words, values, and operators in each statement with spaces. If you don’t, your code will be less readable as illustrated by the second code example in this figure. In this example, each line of code includes at least one operator. Because the operators aren’t separated from the word or value on each side of the operator, though, the code is difficult to read. In contrast, the readable code includes a space on both sides of each operator.

The third recommendation is to use blank lines before and after groups of related statements to set them off from the rest of the code. This too is illustrated by the first procedure in this figure. Here, the code is separated into four groups of statements. In a short procedure like this one, this isn’t too important, but it can make a long procedure much easier to follow.

The fourth recommendation is to use line-continuation characters so long statements are easier to read in the Code Editor window. This also makes these statements easier to read when you print them.

Throughout this chapter and book, you’ll see code that illustrates the use of these recommendations. You will also receive other coding recommendations that will help you write code that is easy to read, debug, and maintain.

By default, the Code Editor automatically formats your code as you enter it. When you press the Enter key at the end of a statement, for example, the Editor will indent the next statement to the same level. In addition, it will capitalize all variable names so they match their declarations, and it will add a space before and after each operator.

A procedure written in a readable style

  Private Sub btnCalculate_Click(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles btnCalculate.Click

      Dim discountPercent As Decimal
      If txtSubtotal.Text >= 500 Then
          discountPercent = 0.2
      ElseIf txtSubtotal.Text >= 250 And txtSubtotal.Text < 500 Then
          discountPercent = 0.15
      ElseIf txtSubtotal.Text >= 100 And txtSubtotal.Text < 250 Then
          discountPercent = 0.1
      Else
          discountPercent = 0
      End If

      Dim discountAmount As Decimal = txtSubtotal.Text * discountPercent
      Dim invoiceTotal As Decimal = txtSubtotal.Text - discountAmount

      txtDiscountPercent.Text = FormatPercent(discountPercent, 1)
      txtDiscountAmount.Text = FormatCurrency(discountAmount)
      txtTotal.Text = FormatCurrency(invoiceTotal)

      txtSubtotal.Select()

  End Sub

Statements written in a less readable style

  dim discountAmount as Decimal=txtsubtotal.Text*discountpercent
  dim invoiceTotal as Decimal=txtsubtotal.Text-discountamount
  txtdiscountpercent.Text=formatpercent(discountpercent,1)
  txtdiscountamount.Text=formatcurrency(discountamount)
  txttotal.Text=formatcurrency(invoicetotal)

Coding recommendations

  1. Use indentation and extra spaces to align statements and clauses within statements so they reflect the structure of the program.
  2. Use spaces to separate the words, operators, and values in each statement. 
     
  3. Use blank lines before and after groups of related statements. 
     
  4. Use line-continuation characters to shorten long lines of code so they’re easier to read in the Code Editor window.

Notes

  1. As you enter code in the Code Editor, Visual Studio may adjust the indentation, spacing, and capitalization so it’s easier to read. This has no effect on the operation of the code.
  2. If Visual Basic doesn’t adjust the code, check the Pretty Listing option in the Options dialog box. To find this option, expand the Text Editor group, the Basic group, and the VB Specific group.

 

Figure 3-7.   How to code with a readable style 

How to code comments

Comments can be used to document what the program does and what specific blocks or lines of code do. Since the Visual Basic compiler ignores comments, you can include them anywhere in a program without affecting your code. Figure 3-8 shows you how to code comments.

The basic idea is that you start a comment with an apostrophe. Then, anything after the apostrophe is ignored by the compiler. As a result, you can code whatever comments you want.

In this figure, you can see four lines of comments at the start of the procedure that describe what the procedure does. You can see one-line comments at the start of blocks of code that describe what the statements in those blocks do. And you can see one example of a comment that follows a statement on the same line.

Although some programmers sprinkle their code with comments, that shouldn’t be necessary if you write your code so it’s easy to read and understand. Instead, you should use comments only to clarify code that’s difficult to understand. The trick, of course, is to provide comments for the code that needs explanation without cluttering the code with unnecessary comments. For example, an experienced Visual Basic programmer wouldn’t need any of the comments shown in this figure.

One problem with comments is that they may not accurately represent what the code does. This often happens when a programmer changes the code, but doesn’t change the comments that go along with it. Then, it’s even harder to understand the code, because the comments are misleading. So if you change the code that has comments, be sure to change the comments too.

Incidentally, all comments are displayed in the Code Editor in a different color from the words in the Visual Basic statements. By default, the Visual Basic code is blue and black (blue for Visual Basic keywords and black for the rest of the code), while the comments are green. That makes it easy to identify the comments.

A procedure with comments

  Private Sub btnCalculate_Click(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles btnCalculate.Click

  ' ========================================================
  ' This procedure calculates the discount and total for an invoice.
  ' The discount depends on the invoice subtotal.
  ' =======================================================

  ' Determine the discount percent
      Dim discountPercent As Decimal
      If txtSubtotal.Text >= 500 Then
          discountPercent = 0.2
      ElseIf txtSubtotal.Text >= 250 And txtSubtotal.Text < 500 Then
          discountPercent = 0.15
      ElseIf txtSubtotal.Text >= 100 And txtSubtotal.Text < 250 Then
          discountPercent = 0.1
      Else
          discountPercent = 0
      End If

  ' Calculate the discount amount and invoice total
      Dim discountAmount As Decimal = txtSubtotal.Text * discountPercent
      Dim invoiceTotal As Decimal = txtSubtotal.Text - discountAmount

  ' Format the discount percent, discount amount, and invoice total
  ' and move these values to their respective text boxes
      txtDiscountPercent.Text = FormatPercent(discountPercent, 1) 
      txtDiscountAmount.Text = FormatCurrency(discountAmount)
      txtTotal.Text = FormatCurrency(invoiceTotal)

      txtSubtotal.Select()      ' Move the focus to the Subtotal text box

  End Sub

Coding recommendations

  1. Use comments only for portions of code that are difficult to understand.
  2. Make sure that your comments are correct and up-to-date.

Description

  1. Comments are used to help document what a program does and what the code within it does.
  2. To code a comment, type an apostrophe followed by the comment. You can use this technique to add a comment on its own line or to add a comment after the code on a line. 
     
  3. During testing, you can comment out lines of code by coding an apostrophe before them. This is useful for testing new statements without deleting the old statements. Another way to comment out one or more lines of code is to select the lines and click on the Comment or Uncomment button in the Text Editor toolbar (see figure 3-10).

 

Figure 3-8.   How to code comments

Please check back next week for the continuation of this article.

blog comments powered by Disqus
VISUAL BASIC.NET ARTICLES

- Basic Form Properties and Modality in VB.NET
- Multiple Document Interfaces in Visual Basic
- Visual Basic for Beginners
- ASP.NET Image to PDF with VB.Net
- MySQL in ASP.NET: Mono using VB.NET
- AsyncFileUpload File Type and File Size Vali...
- Visual Studio: Adding Functionality and Style
- Clocks and Countdowns
- User-defined Functions using Visual Basic Ap...
- Understanding Object Binding in VBA
- Mastering the Message Box
- Testing a Windows Forms Application
- Using Visual Basic.NET Features to Code a Wi...
- Correcting Code in a Windows Forms Applicati...
- Write Readable Code and Comments for Windows...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 4 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials