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

Chapter 4: Refactoring

Refactoring your prime number validator

face Josiah Wang

Ok, now let us try to improve some of our previous codes. Our aim is to make the code more:

  1. reusable (i.e. modular)
  2. self-explanatory (i.e. highly abstracted)

Again, please try it out yourself while you follow along.

Now, let us start with my prime number checker program from the previous lesson.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
n = int(input("Please enter an integer: "))
divisor = 2
is_prime_number = True

while divisor < n:
    if n % divisor == 0:
        is_prime_number = False
        break
    else:
        divisor = divisor + 1

if n > 1 and is_prime_number:
    print(f"{n} is a prime number")
else:
    print(f"{n} is not a prime number")

Does it seem difficult to read at first glance? There is just too much detail in it. It surely took time for me to understand that this is a prime number checker program (and I was the one who wrote this code!)

What about the following code?

1
2
3
4
5
n = int(input("Please enter an integer: "))
if is_prime_number(n):
    print(f"{n} is a prime number")
else:
    print(f"{n} is not a prime number")

Is it easier to read?

I can immediately see that the program reads an integer from a user, and the program checks whether the number is a prime number and prints out the appropriate message.

What is nice about this piece of code is that it did not make me think! I can just read the code and understand it immediately (i.e. self-explanatory), even without knowing the details.

This is one of the powers of using functions - abstraction. You give a higher-level abstraction to your program (which makes it more readable and self-explanatory). At the same time, you hide any details that are irrelevant at that level of abstraction. Can you see how powerful this is?

You can even go further and abstract the bit of code that reads in the number from the user.

1
2
3
4
5
n = read_integer()
if is_prime_number(n):
    print(f"{n} is a prime number")
else:
    print(f"{n} is not a prime number")

Is the code above even easier to read? You do not even need to worry about what message you are showing the user at this level. It is a minute detail that you delegate to read_integer().

It’s Your Turn!

Now, try to implement the is_prime_number() function by moving bits of the original code into this function. The function should return True if the input argument is a prime number, and should return False if it is not a prime number.

If you like, you can also implement read_integer().

Then continue with the lesson.