This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 10: Input validation

Look before you leap!

face Josiah Wang

The first school of thought is that you should “Look Before You Leap (LBYL)”.

This style of programming is also known as defensive programming.

This is like tight airport security that always checks you thoroughly before letting you pass, and always ready to catch any suspects the moment they are spotted. So, you are guilty until proven innocent!

Or like a controlling parent who tells you what you can and cannot do. You know, because they know what’s best for you!

Here is the LBYL (or defensive programming) approach to handling invalid inputs for our example earlier.

1
2
3
4
5
6
def calculate(numerator, denominator):
    if denominator == 0:
        result = 0
    else: 
        result = 2 * (numerator+3) / denominator
    return result

You can also use assert statements for validation if you prefer.

The advantage of this approach that you can try to foresee everything that can go wrong, and then make sure you deal with each case carefully. Your code will thus be very stable and robust.

The disadvantage is that your code will have perform the check every time the function is called, even if you expect the inputs to be correct most of the time. These unnecessary checks can slow down your program, and also ‘bulk up’ your code unnecessarily. A bit like how everyone has to be subject to scrutiny because of a few bad eggs!