FREE BOOK

Chapter 3: How to code and test a Windows Forms application using C# 2008

Posted by Murach Free Book | Windows Forms December 10, 2008
In this chapter, you'll learn how to code and test a Windows Forms application. When you're done, you'll be able to develop simple applications of your own.

More coding skills

At this point, you should understand the mechanics of adding code to a form. To code effectively, however, you'll need some additional skills. The topics that follow present some of the most useful coding skills.

How to code with a readable style

In figure 3-6, you learned some coding rules that you must follow when you enter the code for an application. If you don't, Visual Studio reports syntax errors that you have to correct before you can continue. You saw how that worked in the last figure.

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 three coding recommendations presented in figure 3-8.

To illustrate, this figure presents two versions of an event handler. Both versions accomplish the same task. As you can see, however, the first one is easier to read than the second one because it follows our coding recommendations.

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, tabs, or returns to separate the elements in a C# statement. In this example, all of the statements within the event handler are indented. In addition, the if-else statements 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. In the unreadable code in this figure, for example, you can see that each line of code except for the method declaration includes at least one operator. Because the operators aren't separated from the word or value on each side of the operator, 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 method in this figure. Here, the code is separated into five groups of statements. In a short method like this one, this isn't too important, but it can make a long method much easier to follow. 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.

As you enter code, the Code Editor will automatically assist you in formatting your code. 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. Although you can change how this works using the Options dialog box, you probably won't want to do that.

A method written in a readable style

private void btnCalculate_Click(object sender, System.EventArgs e)
{
        decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);

        decimal
discountPercent = 0m;
        if (subtotal >= 500)
        {
            discountPercent = .2m;
        }
        else if (subtotal >= 250 && subtotal < 500)
        {
            discountPercent = .15m;
        }
        else if (subtotal >= 100 && subtotal < 250)\
        {
            discountPercent = .1m;
        }

        decimal
discountAmount = subtotal * discountPercent;
       
decimal invoiceTotal = subtotal - discountAmount;

        txtDiscountPercent.Text = discountPercent.ToString("p1");
        txtDiscountAmount.Text = discountAmount.ToString("c");
        txtTotal.Text = invoiceTotal.ToString("c");

        txtSubtotal.Focus()
;
}


A method written in an unreadable style

private void btnCalculate_Click(object sender, System.EventArgs e){
decimal subtotal=Convert.ToDecimal(txtSubtotal.Text);
decimal discountPercent=0m;
if (subtotal>=500) discountPercent=.2m;
else if     (subtotal>=250&&subtotal<500)     discountPercent=.15m;
else if     (subtotal>=100&&subtotal<250)     discountPercent=.1m;
decimal   discountAmount=subtotal*discountPercent;
decimal   invoiceTotal=subtotal-discountAmount;
txtDiscountPercent.Text=discountPercent.ToString("p1");
txtDiscountAmount.Text=discountAmount.ToString("c");
txtTotal.Text=invoiceTotal.ToString("c");txtSubtotal.Focus();}

Coding recommendations

  • Use indentation and extra spaces to align statements and blocks of code so they reflect the  structure of the program.

  • Use spaces to separate the words, operators, and values in each statement.

  • Use blank lines before and after groups of related statements.

Note

  • As you enter code in the Code Editor, Visual Studio automatically adjusts its formatting by default.

How to code comments

Comments are used to document what the program does and what specific blocks and lines of code do. Since the C# compiler ignores comments, you can include them anywhere in a program without affecting your code. Figure 3-9 shows you how to code two types of comments.

First, this figure shows a delimited comment at the start of a method. This type of comment is typically used to document information that applies to an entire method or to any other large block of code. You can include any useful or helpful information in a delimited comment such as a general description of the block, the author's name, the completion date, the files used by the block, and so on.

To document the purpose of a single line of code or a block of code, you can use single-line comments. Once the compiler reads the slashes (//) that start this type of comment, it ignores all characters until the end of the current line. In this figure, single-line comments have been used to describe each group of statements. In addition, single-line comments have been used at the end of some lines of code to clarify the code.

Although many 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 C# 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 green by default, which is different from the color of the words in the C# statements. That makes it easy to identify the comments. Chapter 3 How to code and test a Windows Forms application 75

A method with comments

private void btnCalculate_Click(object sender, System.EventArgs e)
{
        /***************************************
        * this method calculates the total
        * for an invoice depending on a
        * discount that's based on the subtotal
       
****************************************/

        // get the subtotal amount from the Subtotal text box
        decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);

        // set the discountPercent variable based
        // on the value of the subtotal variable
        decimal discountPercent = 0m; // the m indicates a decimal value
        if (subtotal >= 500)
        {
            discountPercent = .2m;
        }
        else if (subtotal >= 250 && subtotal < 500)
        {
            discountPercent = .15m;
        }
        else if (subtotal >= 100 && subtotal < 250)
        {
            discountPercent = .1m;
        }
       
        // calculate and assign the values for the
        // discountAmount and invoiceTotal variables
        decimal discountAmount = subtotal * discountPercent;
        decimal invoiceTotal = subtotal - discountAmount;

        // format the values and display them in their text boxes
        txtDiscountPercent.Text =             // percent format
            discountPercent.ToString("p1"); // with 1 decimal place
        txtDiscountAmount.Text =
            discountAmount.ToString("c");  // currency format
        txtTotal.Text =
        invoiceTotal.ToString("c");

        // move the focus to the Subtotal text box
        txtSubtotal.Focus();
}


Description

  • Comments are used to help document what a program does and what the code within it does.

  • To code a single-line comment, type // before the comment. You can use this technique to add a comment on its own line or to add a comment at the end of a line.

  • To code a delimited comment, type /* at the start of the comment and */ at the end. You can also code asterisks to identify the lines in the comment, but that isn't necessary.

Total Pages : 10 56789

comments