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

Chapter 9: Refactoring the robot

Your top-level algorithm

face Josiah Wang

How was that? Happy with what you came up with?

Your top level algorithm might look something like this:

1. Read in robot name
2. Generate an ID for robot
3. Assign random initial robot position
4. Assign random initial robot direction
5. Print robot greeting
6. Navigate to Ribena

If this looks something like your list, great. If not, maybe your solution is better?

Now, is there any scope to make this list even more high level?

Look at the first four tasks. It feels like we can group these tasks together, doesn’t it? Maybe we can group these steps into a single higher-level task called set up robot. So, now, your top-level algorithm might look like this.

1. Set up robot
2. Print robot greeting
3. Navigate to Ribena

Can you imagine your short main program already? It will now be three function calls. One to set up the robot, the second to print out the greeting, the third to perform the robot navigation. Does not sound like it is going to be a difficult program to write now, does it?

Then you can start thinking about the details of each of the function.

Of course, each of the function above can have more subtasks. So, now, let’s try to break down each function further.

For example, to set up a robot (first task), you will need to perform the four subtasks that we grouped together earlier:

Set up robot
1.1. Read in robot name
1.2. Generate an ID for robot
1.3. Assign random initial robot position
1.4. Assign random initial robot direction

Each of these could potentially be a function. Now continue drilling down each of these tasks until you feel that you cannot break it down further. Look at your existing code if you need to – can some of what you previously wrote be abstracted away further?

For example, Read in robot name seems precise enough that no other subtasks is needed. So this can be a good “fine-grained level” function.

Try completing this exercise for all the other tasks. You can also think of each of these task list as an algorithm, not just a list. So do use while loops or if statements if needed!

Ideally, by the end of this, you will have a hierarchy of post-it notes, with each note being an algorithm, and arrows from each task pointing to their subnotes etc.

When you have finished, move on to the next page!