Hour 8. Structured Techniques

Now you are familiar with the steps to take before programming. You also know how to do some programming, having a little JavaScript in your programming bag of tricks. In this hour’s lesson, you begin honing your programming skills. From Hour 3, “Designing a Program,” you now know that two steps must always precede writing the program—defining the output and data as well as developing the logic. After you develop the logic, you can write the program, using one of the many available programming languages.

This hour guides you into being a more structured programmer, writing clearer code, and writing code that is maintainable. Your future as a programmer depends on your being able to write code that others can change and manage.

The highlights of this hour include the following:

Image Understanding the importance of structured programming

Image Analyzing the three structured-programming constructs

Image Testing a program

Image Checking a program in stages

Image Using parallel testing to eliminate downtime

Structured Programming

Structured programming is a philosophy stating that programs should be written in an orderly fashion without a lot of jumping to and fro. If a program is easy to read, the program is easier to change. People have known for many years that clear writing style is important, but it became obvious to computer people only after nearly 20 years of using nonstructured techniques.

In the late 1960s, programming departments began to wallow in programming backlogs that grew at tremendous rates. More people were writing more programs than ever, but many programmers had to be hired to maintain the previously written programs.


Tip

You cannot hear the importance of writing readable and maintainable programs too often. By using a conscientious approach (instead of the old “throw a program together” approach that some programmers use), you help ensure your future as a programmer. Companies save money when a programmer writes code that is easily maintained.


When you finish a program, you are finished only for the time being. That program’s assumptions about the job that it performs will change over time. Businesses never remain constant in this global economy. Data processing managers began to recognize that the programming maintenance backlog was beginning to take its toll on development. Programmers were pulled away from new projects in order to update older projects. The maintenance was taking too long.

By the way, the programming backlog of the 1960s has never really gotten better. Companies all around the world keep contract programmers and programming staff on hand to develop the new systems that they need. A backlog of computer projects seems to be the norm in the computer world. Constant change in the world means that an organization’s data processing has to change as well.

Roots of Structured Programming

During the maintenance crisis of the 1960s, data processing people began looking for new ways to program. They weren’t necessarily interested in new languages but in new ways to write programs that would make them work better and faster and, most important, make them readable so that others could maintain the programs without too much trouble. Structured-programming techniques were developed during this time.

There is some debate as to exactly when beginning programmers should be introduced to structured programming. Some people feel that programmers should be trained in structured programming from the beginning. Others feel beginners should learn to program any way that gets the job done, and then they should adapt to structured programming.

You’ve seen what flowcharts are, and the rest of this hour will use those tools to show you what structured programming is all about. As mentioned in Hour 3, flowcharts are not used so much anymore to design complete programs but are used for showing small logic flows. It is a good idea to incorporate structured-programming techniques into your code-writing process. Many of today’s languages naturally lend themselves to structured-programming techniques because their commands and structure mirror the structured-programming rules you’ll learn in the next sections.

Looking at Structure

Just because a program is well written and easily read doesn’t necessarily mean it’s structured. Structured programming is a specific approach to programming that generally produces well-written and easily read programs. Nothing can make up for a programmer rushing to finish a program by proceeding in what he thinks is the fastest way. You often hear, “Later, I’ll make it structured, but for now, I’ll leave it as it is.” Later never comes. People use the program until one day, when changes have to be made, the changes turn out to take as long as or longer than it would take to scrap the entire program and rewrite it from scratch.

Structured programming includes the following three constructs:

Image Sequence

Image Decision (also called selection)

Image Looping (also called repetition or iteration)

A construct (from the word construction) is a building block of a language and one of a language’s fundamental operations. As long as a programming language supports these three constructs (most modern languages do), you can write structured programs. The opposite of a structured program is known as spaghetti code. Like spaghetti that flows and swirls all over the plate, an unstructured program—one full of spaghetti code—flows all over the place with little or no structure. An unstructured program contains lots of branching. A branch occurs when a program goes this way and that with no particular order.


Jumping Around

Most programming languages enable you to branch with a goto statement. The goto works just as it sounds: it tells the computer to go to another place in the program and continue execution there. While JavaScript reserved the keyword goto (meaning you cannot use it as a variable or function name), It does not have a goto statement, so you don’t have to worry about learning what it does and then not using it. However, if you work with other languages you will see this technique used, but it should be avoided whenever possible.


The three structured-programming constructs aren’t just for programs. You will find that you can use them for flowcharts, pseudocode, and any other set of instructions you write for others, whether those instructions are computer-related or not. The three structured-programming constructs ensure that a program doesn’t branch all over the place and that any execution is controlled and easily followed.

The following three sections explain each of the three structured-programming constructs. Read them carefully and you’ll see that the concept of a structured program is easy to understand. Learning about structure before learning a language should help you think of structure as you develop your programming skills.

Sequence

Sequence is nothing more than two or more instructions, one after the other. The first few programs you wrote in JavaScript use sequence. The sequential instructions are the easiest of the three structured-programming constructs because you can follow the program from the first statement to the last within the sequence. Figure 8.1 shows a flowchart that illustrates sequence.

Image

FIGURE 8.1 The sequence structured-programming construct executes the program in order.

To show that you can represent any kind of logic using pseudocode as well as a flowchart, here is pseudocode that matches the sequence of the flowchart:

Get the hours worked.
Multiply the hours by the rate.
Subtract taxes to compute net pay.
Print paycheck.


Note

Some programmers prefer to see pseudocode when looking at logic instead of flowcharts because of pseudocode’s compact nature and its closeness to actual computer code.


Because computers must have the capability of making decisions and performing repetitive tasks, not all your programs can consist of straight sequential logic. When sequence is available, however, it makes for straightforward program logic.

Decision (Selection)

You have seen the decision construct before. In JavaScript, when you wrote an if statement, you were using the structured-programming decision construct. At the point of such a decision, the program must take off in one of two directions. Obviously, a decision is a break from the sequential program flow, but it’s a controlled break.

By its nature, a branch must be performed based on the result of a decision (in effect, the code must skip the code that is not to execute). Based on new data, the program might repeat a decision and take a different route the second time, but again, you can always assume that the decision code not being executed at the time is meaningless to the current loop.

Figure 8.2 shows a flowchart that contains part of a teacher’s grading program logic. The flowchart illustrates the use of the decision construct.

Image

FIGURE 8.2 The decision structured-programming construct offers one of two choices.

Here is the pseudocode for the decision shown in the flowchart:

If the student makes an A or B,
  give the student an achievement certificate.
Otherwise:
  set up a parent-teacher conference;
give the student extra homework.

Looping (Repetition and Iteration)

Perhaps the most important task of computers is looping (the term for repeating or iterating through lines of program code as you did in Hour 6, “Controlling Your Programs”). Computers repeat sections of a program millions of times and never become bored. Computers are perfect companions for workers who have lots of data to process, because the computer can process the data, repeating the common calculations needed throughout all the data, and the person can analyze the results.

Looping is prevalent in almost every program written. Rarely do you write a program that is a straight sequence of instructions. The time it takes to design and write a program isn’t always worth the effort when a straight series of tasks is involved. Programs are most powerful when they can repeat a series of sequential statements or decisions.

Figure 8.3 shows a flowchart that repeats a section in a loop. Loops only temporarily break the rule that says flowcharts should flow down and to the right. Loops within a flowchart are fine because eventually the logic will stop looping.

Image

FIGURE 8.3 The looping structured-programming construct repeats parts of the program.


Caution

Be aware of the dreaded infinite loop. An infinite loop is a never-ending loop. If your computer goes into an infinite loop, it continues looping, never finishing, and sometimes it’s difficult to regain control of the program without rebooting the computer. Loops should always be prefaced with a decision statement so that eventually the decision triggers the end of the loop and the rest of the program can finish.


Here is the pseudocode for the flowchart:

If there are more customers,
  do the following:
    calculate the next customer's balance;
    print an invoice.
Otherwise,
  print the total balance report.

As you can see, eventually there won’t be any customers, and the loop (beginning with do) will stop looping so that the rest of the logic can take over.

None of these structured-programming constructs should be new to you because you worked with them in the JavaScript programs. As long as you keep these three constructs in mind while you develop your program’s logic, and as long as you resist the temptation to start branching all over the program, you will write well-structured, easy-to-maintain programs and secure your position as a programmer for many years to come.

Packaging Your JavaScript Code into Functions

When writing your programs, you often find that you have to perform specific jobs repeatedly. To save time, you can create a function and then re-use it in any JavaScript program you write. These resusable bits of code are similar to the methods you have seen to date, like the math and string methods. Writing functions is not limited to JavaScript either; it is a fundamental practice of structured programs in most other languages as well.

Creating Functions

Suppose you noticed you always needed to cut your variable values in thirds (perhaps you have three kids and need to divide everything equally among them). Rather than constantly write the code needed to divide your variables in three, you decide to create a function to do it for you. The following code would do it for you:

function cutthird (x) {
       var y = x / 3;
       return y;
}

The x in the parentheses can be any value. You can replace it with an actual number (6) or a variable. The function will take that number, divide it by 3, and then return the new value. The keyword return is probably new to you. If your function is going to perform some operation on a variable, you need to get the new value back to your original code. The return keyword tells your program to send some value back to the calling function. Now to use the function in your code, you could call it in the following manner:

candy = prompt("How many pieces of candy in the bag?");
var candyperkid = cutthird(candy);
document.write("Each kid gets " + candyperkid + " pieces");

So in this case you’ve created a new variable, candyperkid, and set it to the value that your function calculates. You can then call the function as often as you want, just as you can call any string or math method as often as you want.

LISTING 8.2 Collecting your functions into a .js file


// Filename: storefunctions.js
// A file that collects the functions
// for Fran's Place in a single file

function storeInfo() {
 document.write("Welcome to Fran's Place!<br>");
 document.write("103 Main Street<br>");
 document.write("Wabash, IN 48673<br>");
 document.write("Open daily 7AM-10PM<br>")
 document.write("Call us at 260-555-1244<br>");
 document.write("Visit our website www.fransplace.com<br>");
}


LISTING 8.3 storeinfo2.html. Similar function as Listing 8.1, but adding a separate file with the function


<! DOCTYPE html>
<html>
<head>
       <title>Fran's Place</title>
       <script src='storefunctions.js'></script>
</head>
<body>

       <script>

       // Filename: Storeinfo2.html
       // A function that lists the info
       // for Fran's Place in a typical function


       // Call the function to test it

       storeInfo();
       document.write("<p><p>Apples on Sale!<br>");
       document.write("3 lbs. for $2.00!<br>");


       </script>
</body>
</html>


Once you create a .js file with your saved code, to include it you just need to use the script src line, <script src=’storefunctions.js’></script>. This assumes that the .js file is in the same folder as your HTML file. If it isn’t, you can add the file path to your file name such as

<script src='c:/My Documents/code/store/storefunctions.js'></script>

You can place this command in the head of your HTML file, or you can place it in the body of the HTML file.

Now it may not seem like you’re saving much time if you compare the work you would put into Listing 8.1 versus Listings 8.2 and 8.3. But this is the simplest example and only has one function. Perhaps you’ll decide to add another function, such as turning the cash register prompts from Hour 4 into a function. That could be added to your storefunction.js file.

Another value of collecting a function into a single file is if you need to alter your information for your store. Perhaps you decide to stay open to 11 every night instead of 10. If you’ve created 20 web pages for your store and each individual page has that information, you need to change all 20. If the 20 pages all use the function file, changing it there will cause all the web pages to be updated.

Testing the Program

When you finish writing the actual program code with your structured format and your functions, you aren’t completely done with the program. You must turn to the task of debugging the program using the methods described in Hour 7, “Debugging Tools.” You know that you need to eliminate as many bugs from the program as possible. For obvious reasons, you don’t want the user to do this. You don’t want the user of your program finding all kinds of mistakes that you made. Therefore, you must thoroughly test the program.

Knowing how to debug is only the first step in writing trouble-free programs. You already know what to do if bugs appear, but before you release a program for use, you need to ensure that you have put that program through thorough testing so that few, if any, bugs ever appear.

Here are the typical testing steps that programmers should follow before distributing a final version of a program to users:

1. Perform desk checking.

2. Perform a beta test.

3. Compare the results of the beta test against the old system’s parallel test results.

Desk Checking

Most programmers go through a series of desk checks on their programs. Desk checking is the process of sitting in front of a computer and checking the program by using as many different scenarios of data as possible to find weak spots and errors in the code. During desk checking, programmers should try extreme values, type bad input, and generally try their best to make the program fail. Programmers should also try every option available in the program, using different combinations to see what happens in all situations.

Beta Testing

When desk checking is completed and programmers are as confident as they can be about the program’s correctness, programmers should set up a group of users to try the program. This is known in the industry as the beta testing stage. The more beta testers (test users of the program) you find to test the program, the better the chance that errors will be found. Users often try things the programmer never thought of while writing the program.


Beta Testing Now Exists on a Grand Scale

More and more companies are openly inviting the public to help beta-test products. Microsoft, for example, is extremely open about distributing beta-test copies of its applications and operating systems long before the final release is available for sale. Most of these beta versions are available for download over the Internet. These beta-test products give reviewers and testers an early peek at the software, which also helps Microsoft because these testers can inform Microsoft of bugs they find.

As the beta audience grows, so does the time a company takes for the test. The problem is that today’s software is highly complex, requiring as many as a few hundred programmers to produce a product, such as a new version of Windows. A large-scale beta test is about the only way that these companies can discover some of the bugs that must be fixed before the product is released.


Parallel Testing

The user should never abandon an old system and switch to the new program right away. Parallel testing should be performed. For instance, if you write a payroll program to replace the manual payroll system for a dry cleaner, the dry cleaner shouldn’t receive a copy of your program and use only that. Instead, the dry cleaner should continue its manual payroll system and use your program at the same time. Although this means that the payroll function takes a little longer each pay period, you can compare the results of the program with those of the manual system to see whether they match.

Only after several pay periods of well-matched parallel testing should the user feel confident enough to use the program without the manual backup.

During this testing period, programmers might have to make several changes to the program. Expect that changes will be necessary, and you won’t feel disappointed or lose your programming confidence. Programmers rarely write a program correctly the first time. It usually takes many attempts to make programs correct. The thorough testing described in this section doesn’t ensure a perfect program. Some errors might appear only after the program has been used for a while. The more testing you do, the less likely it is that errors will creep up later.

Profiling Code

A profiler is a program that monitors the execution of your program, looking for sluggish code that might be optimized for speed or size. Many of today’s compilers are optimizing compilers that try to take your code and turn it into the fastest possible machine code, but there is always room for improvement. On average, 5% of a program takes 95% of the program’s execution time. The profiler can help you improve the speed and efficiency of your program.

Advanced programming systems such as Visual C++ come with profiling tools that help you locate sluggish areas of your program. You cannot always speed up a program, but if parts of a program are slowing down the overall operation, you might be able to optimize the code to keep the program flowing smoothly. A profiler can also help you pinpoint when files get so large that faster disk drives and more memory might be beneficial to the operation of a program.

Getting Back to Programming

You’re probably ready to get back into the foray of programming. That’s good, because it’s time to do just that. You now have some groundwork that many newcomers to programming never get. You know the importance of writing clear and concise code. You also know the importance of testing the program before you put the program into production, and you know how to debug any problems that you might find.

The rest of this part of the book focuses on improving your programming skills by teaching you some fundamental programming topics such as data searching, graphics, and programming for the Windows environment.

Summary

The programming process requires more than sitting at the keyboard. Proper design is important, as are structured-programming techniques and proper testing. You and others can easily maintain a well-written program. Because of the changing world and the high maintenance requirements of programs, you should attempt to learn structured-programming techniques that help clarify programs. The three structured-programming constructs that you are now familiar with are sequence, decision, and looping. You also can save time and avoid repetition of code by creating functions.

The next hour explains some advanced programming concepts that you can apply to search for data. You’ll be back in front of the keyboard for a few more hours with JavaScript to get you ready for the next step, which begins the third part of this book: object-oriented programming.

Q&A

Q. How much testing is enough?

A. You can never test too much, but resources and the user’s request for the program certainly bear on the decision to stop testing. If you know bugs exist in the program, you must remove them, so testing will help ensure that you’ve fixed all that you can fix.

Q. What tools are available to help me test my program?

A. Most of today’s integrated debuggers are highly efficient at helping you spot and remove errors in your programs. You saw some of these in the previous hour when you used JavaScript’s debugger to locate problems, examine values, and test programs.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. Why is the programming backlog still around?

2. Why do some programmers prefer to use and view pseudocode for logic design instead of flowcharts?

3. What is the opposite of spaghetti code?

4. What are the three structured-programming constructs?

5. Although not in JavaScript, what statement do other programming languages use for branching?

6. Why can excessive branching be bad?

7. Write a function that takes an amount and calculates 6 percent sales tax on the amount and returns that value.

8. Which comes first, desk checking or beta testing?

9. What is the difference between parallel testing and beta testing?

10. What is a profiler?

Answers

1. Computers are used more and more, and new programs need to be written while older programs need to be updated.

2. Flowcharts can consume far too much space on paper for large systems and are cumbersome to draw.

3. Clean, easily maintainable, well-structured code is the opposite of spaghetti code.

4. The three structured programming constructs are sequence, decision, and looping.

5. The goto statement branches to another part of the program.

6. Too much branching makes a program difficult to follow and maintain.

7. Yours might look slightly different, but as long as you get to the right answer, style is personal:

function calculateTax(product)
{
      var taxrate = .06;
      tax = product * taxrate;
      return (tax);
}

8. Desk checking must precede beta testing.

9. When one parallel tests, the old system is used in conjunction with the new system and the results are compared.

10. A profiler analyzes a program for inefficient code.

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

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