Tuesday, March 30, 2010

Introduction to Programming:Starting Out With Programming Logic and Design; Chapter 7:Input Validation

Starting Out with Programming Logic and Design (2nd Edition)

1. Garbage In, Garbage Out

If you put bad data into a program you will get bad information out. Programs need to be designed to reject bad data. This is known as input validation.

2. The Input Validation Loop

A common technique for validation is an input validation loop. As long as there is bad data in the input the loop will continue. It is generally a pretest loop. The process:

  1. Get the data
  2. Is it good - yes drop out, if no go on to 3
  3. Display error message
  4. Get the data again
  5. Go to step 2

If the data is bad the first time it will be input at least twice.

Using a posttest Loop to Validate Input

While the logic will work to use a posttest it will not show an error message but just keep asking for input.

Writing Validation Functions

Some validations are not as easy as these are. If we had to test for several different values, to make it easier to read, a function could be used. The function could return a Boolean value and as long as it is false the loop will continue.

Validating String Input

If you need to validate string input it is possible that the input may not be in the case that you need it to be. In that case you may need to use a function like toLower or toUpper to change the case. Or in the case of passwords a length may need to be checked with a length function.

3. Defensive Programming

The examples shown so far are what are known as defensive programming, finding mistakes in input as the user puts them in and before they can cause trouble. Other examples include:

  • Empty input - hit enter when asked for data
  • Putting in the wrong data type - real for integer
  • Invalid state code or zip code for addresses
  • Hours worked in a week being unreasonably high

There are many others as well, it is up to the programmer to think of the ones that can affect his program.

 

Defensive programming



No comments:

Post a Comment