Introduction: Making Programs Bulletproof

Welcome to one of the most practical chapters in H2 Computing! Have you ever wondered why a website tells you your password is too short, or why a program suddenly "crashes" when you type a letter instead of a number?

In this chapter, we will learn how to prevent these issues. We’ll explore Data Validation (making sure the input is sensible), Program Testing (finding bugs before your users do), and Error Handling (making sure your program fails gracefully). Learning these skills is what turns a "hobbyist coder" into a professional programmer.

1. Validation vs. Verification: What's the Difference?

People often use these words interchangeably, but in Computing, they mean very different things.

Data Validation is an automatic check carried out by the computer to ensure that the data entered is sensible and follows certain rules. It doesn't guarantee the data is correct, only that it is allowed.

Data Verification is a check to ensure that the data entered exactly matches the original source.

An Everyday Analogy

Imagine you are signing up for a new gym membership:
- Validation: The computer checks if your "Age" is a number between 12 and 100. If you type "200", it rejects it because it’s not sensible.
- Verification: The staff looks at your Identity Card to make sure the name you typed on the screen is actually your real name.

Key Takeaway

Validation checks if the data is sensible.
Verification checks if the data is correct.

2. Data Validation Techniques

To keep "garbage" out of our systems, we use several specific checks. Don't worry if this list looks long; most are very intuitive!

1. Presence Check
Ensures that a field has not been left blank.
Example: A "Required" star next to the Email field in a form.

2. Existence Check
Checks if the data entered already exists in the system or is a valid item in a list.
Example: When you try to register a username and the system says, "Username already taken."

3. Range Check
Checks if a number falls within a specific set of boundaries.
Example: An exam score must be between \(0\) and \(100\).

4. Length Check
Ensures the input has a specific number of characters or is within a certain length range.
Example: A Singapore phone number must be exactly 8 digits long.

5. Type Check
Ensures the data is of the correct data type (e.g., integer, string, float).
Example: Entering "Five" instead of "5" in a quantity box would fail a type check.

6. Format Check
Checks that the data follows a specific pattern or "mask."
Example: A Date must be in the format DD/MM/YYYY.

7. Check Digit
This is a special digit (usually the last one) calculated from the other digits in a number. It is used to detect errors in manual data entry (like swapping two numbers).
Example: The last character in an NRIC or a barcode.

Memory Aid: "P.E.R.F.L.T"

Think of PERFect Little Techniques:
Presence, Existence, Range, Format, Length, Type (and don't forget the Check Digit!).

3. Identifying and Correcting Errors

Even the best programmers make mistakes! There are three main types of errors you need to know:

A. Syntax Errors

These are "grammar" mistakes in your code. The program will not run at all.
Example: Writing prnt("Hello") instead of print("Hello") or forgetting a colon after an if statement.

B. Runtime Errors

The code is written correctly (no grammar mistakes), but something goes wrong while the program is running, causing it to crash.
Example: Division by zero or trying to open a file that doesn't exist.

C. Logic Errors

The program runs without crashing, but it gives the wrong answer. These are the hardest to find!
Example: You want to calculate the area of a square but you write Area = Side + Side instead of Area = Side * Side.

Quick Review

- Syntax: Won't start (Code Grammar).
- Runtime: Crashes midway (Execution Panic).
- Logic: Wrong result (Brain Freeze).

4. Designing Test Cases

To make sure your program works, you must test it with different types of data. Suppose we are testing a program that accepts a student's age (Range: 13 to 18).

1. Normal Data
Data that is well within the acceptable limits.
Example: 15, 16.

2. Boundary (Extreme) Data
Data at the very edges of the range. Errors often happen here!
Example: 13 and 18.

3. Erroneous (Invalid) Data
Data that is outside the range or the wrong type. The program should reject this.
Example: 12, 19, "Hello", or \( -1 \).

Common Mistake to Avoid

Students often forget to test Boundary Data. Always test the exact minimum and maximum values! For a range of 1 to 100, your test cases should definitely include 1 and 100.

5. Program Tracing: Being the Computer

Tracing is the process of following the execution of a program step-by-step to see how variable values change.

Trace Tables (For Non-Recursive Programs)

A Trace Table is a grid where each column represents a variable, and each row represents a step in the program.

Pro-tip: When filling a trace table, only write down a value when it changes. If a value stays the same, leave the cell blank or use a ditto mark to keep it clean.

Recursion Trees (For Recursive Programs)

For functions that call themselves, a table can get messy. Instead, we use a Recursion Tree.

1. Start with the initial call at the top.
2. Draw branches for every time the function calls itself.
3. Write the return values as they "bubble up" back to the top.

Don't worry if this seems tricky at first! Recursion trees are just a map of the function's "journey."

6. Error and Exception Handling

Sometimes, errors are unavoidable (like a user unplugging the internet during a download). Instead of letting the program crash, we use Exception Handling.

In Python, we use the try...except block:

try:
    # Code that might cause an error
    number = int(input("Enter a number: "))
    result = 10 / number
except ZeroDivisionError:
    # What to do if they enter 0
    print("You cannot divide by zero!")
except ValueError:
    # What to do if they enter "hello"
    print("That wasn't a number!")

Key Takeaway

Exception handling makes your program robust. It allows the program to tell the user what went wrong and continue running instead of simply disappearing.

Final Encouragement: You've made it through the basics of Data Validation and Program Testing! Remember, the goal of this chapter isn't just to pass an exam—it's to help you build software that people can actually trust. Keep practicing those trace tables!