Chapter 4: Refactoring

Refactoring your prime number generator

face Josiah Wang

Did you get far with the prime number generator? Have you managed to reuse your functions? Does your code feel more like English and easier to read now?

Here is my implementation. Compare it to yours to see whether/how they are different.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def read_integer():
    entry = input("Please enter an integer: ")
    return int(entry)


def is_divisible_by(number, divisor):
    return number % divisor == 0


def is_prime_number(number):
    if number <= 1:
        return False

    divisor = 2
    while divisor < number:
        if is_divisible_by(number, divisor):
            return False
        else:
            divisor += 1
    return True


def generate_prime_numbers(maximum):
    n = 2
    while n <= maximum:
        if is_prime_number(n):
            print(n)
        n += 1


last_number = read_integer()
generate_prime_numbers(last_number)

I don’t know about you, but I find it more relaxing to read and write this code compared to the original one. Mainly because everything is divided into meaningful abstracted functions, and each function implements a small focused part of the whole program.

I can just read the main program (only two lines! Lines 31-32) and know that this program reads in a number, and generate prime numbers up to the number. And the program generates prime numbers by starting from 2 till this number, and prints out each number if it is prime. We do not even need to know how to check whether the number is prime. It’s not necessary at this level of abstraction - we’ll trust that is_prime_number() will do the right thing. If you really need to know, then you can in turn check the function definition of is_prime_number() and so on.

The task of writing a prime number generator becomes easy if you have already developed your is_prime_number() function. Not counting the 2 lines in the main program, I basically only wrote 6 lines of code to generate prime numbers!

Hopefully I have convinced you that you should write your program in such a modular way. Again, I would like to see your code structured this way from now on! I definitely prefer this over a big blob of code with three nested loops (a sign that you should refactor your code!)