Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Module 4A COMPUTER PROGRAMMING 2

This document discusses input validation techniques in programming. It covers the concepts of garbage in, garbage out and defensive programming. Input validation is commonly done with loops that iterate until valid input is received. Techniques discussed include priming reads, pretest and posttest loops, compound boolean expressions to check multiple conditions, and functions to simplify validation logic. Examples demonstrate validating data types like numbers, strings, passwords. Defensive programming aims to anticipate errors by thoroughly validating all user input.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Module 4A COMPUTER PROGRAMMING 2

This document discusses input validation techniques in programming. It covers the concepts of garbage in, garbage out and defensive programming. Input validation is commonly done with loops that iterate until valid input is received. Techniques discussed include priming reads, pretest and posttest loops, compound boolean expressions to check multiple conditions, and functions to simplify validation logic. Examples demonstrate validating data types like numbers, strings, passwords. Defensive programming aims to anticipate errors by thoroughly validating all user input.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Module 4

Chapter 7:
Input Validation
7.1 Garbage In, Garbage 7.2 The Input Validation 7.3 Defensive
Out Loop Programming
7.1 Garbage In, Garbage Out
CONCEPT: If a program reads bad data as input, it will produce bad data as output.
Programs should be designed to reject bad data that is given as input.
If a program reads bad data as input, it will produce bad data as output
Programs should be designed to accept only good data
❖ Program 7-1 Payroll program, notice what happens in the sample run when the user
gives bad data as input.
7.2 The Input Validation Loop
CONCEPT: Input validation is commonly done with a loop that iterates as long as an
input variable contains bad data.
➢ All input should be inspected before processing
➢ If it’s invalid, it should be rejected and the user should be prompted to enter the
correct data
❖ Figure 7-1 shows a common technique for validating an item of input.
• The input is read, and then a pretest loop is executed.
• If the input data is invalid, the body of the loop executes.
• The loop displays an error message so the user will know that the input was
invalid, and then the loop reads the new input.
• The loop repeats as long as the input is invalid.

In Figure 7-1 reads input in two places: first just before the loop and then inside the loop.

• The first input operation—just before the loop—is called a priming read, and its
purpose is to get the first input value that will be tested by the validation loop. If
that value is invalid, the loop will perform subsequent input operations.
❖ Example. Suppose you are designing a program that reads a test score and you want to
make sure the user does not enter a value less than 0. The following pseudocode shows
how you can use an input validation loop to reject any input value that is less than 0.
// Get a test score.
Display "Enter a test score."
Input score

// Make sure it is not less than 0.


While score < 0
Display "ERROR: The score cannot be less than 0."
Display "Enter the correct score."
Input score
End While
o This pseudocode first prompts the user to enter a test score (this is the priming read),
and then the While loop executes.
o Recall from Chapter 5 that the While loop is a pretest loop, which means it tests the
expression score < 0 before performing an iteration.
o If the user entered a valid test score, this expression will be false and the loop will not
iterate.
o If the test score is invalid, however, the expression will be true and the statements in
the body of the loop will execute.
o The loop displays an error message and prompts the user to enter the correct test score.
The loop will continue to iterate until the user enters a valid test score.
NOTE: An input validation loop, such as the one in Figure 7-1, is sometimes called an error
trap or an error handler.
This pseudocode only rejects negative test scores. What if you also want to reject any test
scores that are greater than 100? You can modify the input validation loop so it uses a
compound Boolean expression, as shown next.

The loop in this pseudocode determines whether score is less than 0 or greater than 100. If
either is true, an error message is displayed and the user is prompted to enter a correct score.

Designing an Input Validation Loop


In Chapter 5 you saw a program that your friend Samantha can use to calculate the retail price
of an item in her import business (see Program 5-6 in Chapter 5). Samantha has encountered a
problem when using the program, however. Some of the items that she sells have a wholesale
cost of 50 cents, which she enters into the program as 0.50. Because the 0 key is next to the key
for the negative sign, she sometimes accidentally enters a negative number. She has asked you
to revise the program so it will not allow a negative number to be entered for the wholesale
cost.
You decide to add an input validation loop to the showRetail module that rejects any negative
numbers that are entered into the wholesale variable. Program 7-2 shows the new
pseudocode, with the new input validation code shown in lines 28 through 33.
Figure 7-2 shows a new flowchart for the showRetail module.
Using a Posttest Loop to Validate Input
Example, the pseudocode to get a test score and validate it could be written as follows with a
Do-While loop.

Although this logic will work, it does not display an error message when the user enters an
invalid value—it simply repeats the original prompt each time the loop iterates. This might be
confusing to the user, so it is usually better to have a priming read followed by a pretest
validation loop.

Writing Validation Functions


Example. Suppose you are designing a program that prompts the user to enter a product model
number and should only accept the values 100, 200, and 300. You could design the input
algorithm as shown next.

The validation loop uses a long compound Boolean expression that will iterate as long as model
does not equal 100 AND model does not equal 200 AND model does not equal 300. Although
this logic will work, you can simplify the validation loop by writing a Boolean function to test the
model variable and then calling that function in the loop.
For example, suppose you pass the model variable to a function you write named isInvalid. The
function returns True if model is invalid, or False otherwise. You could rewrite the validation
loop as follows:
This makes the loop easier to read. It is evident now that the loop iterates as long as model is
invalid. The following pseudocode shows how you might design the isInvalid function. It accepts
a model number as an argument, and if the argument is not 100 AND the argument is not 200
AND the argument is not 300, the function returns True to indicate that it is invalid. Otherwise,
the function returns False.

Validating String Input


Example, suppose you are designing a program that asks a yes/no question, and you want to
make sure that only the strings "yes" or "no" are accepted as valid input. The following
pseudocode shows how this might be done.

o This input validation loop rejects any input except the strings "yes" and "no".
o This particular design might be too rigid, however; as it is written, the loop performs a
case-sensitive comparison. This means that strings such as "YES", "NO", "Yes", and "NO"
will be rejected.
o To make the program more convenient for users, the program should accept "yes" and
"no" written in any combination of upper- or lowercase letters.
Library functions such as toUpper and toLower can help make case-insensitive string
comparisons. The following pseudocode shows an example using the toLower function.
Sometimes the length of a string plays a role in the string’s validity.

❖ For example, you have probably used a Web site or other system that required you to
set up a password. Some systems require that passwords have a minimum number of
characters.
In the following pseudocode, the length function is used to make sure a password is at
least six characters long.

7.3 Defensive Programming


CONCEPT: Input validation is part of the practice of defensive programming. Thorough
input validation anticipates both obvious and unobvious errors.
Defensive programming - the practice of anticipating errors that can happen while a program is
running, and designing the program to avoid those errors.
Types of errors to consider
– Empty input, where a user accidentally hits enter before entering data
– The user enters the wrong type of data
Common errors to be aware of
– State abbreviations should be 2-character strings
– Zip codes should be in the proper format of 5 or 9 digits
– Hourly wages and salary amounts should be numeric values and within ranges
– Dates should be checked
– Time measurements should be checked
– Check for reasonable numbers

You might also like