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

Top down redesign

face Josiah Wang

You have done some refactoring earlier.

You probably mainly used a bottom-up approach for that. That is, you restructured your code by directly finding bits of codes that can be turned into functions, and just updated your code directly.

I am concerned that you might find that a bit overwhelming for your robot project, which have grown considerably since you first created it. Believe me - I’ve tried doing this myself!

So, this time, let us try mixing in some “top down” style restructuring of your code.

To make it easier to work, rename your main.py to main_old.py. Then create a new blank file main.py. We will restructure your code in main.py, and you can copy any bits of existing code from main_old.py when needed.

user@MACHINE:~/robot$ mv main.py main_old.py
user@MACHINE:~/robot$ touch main.py

Now, remember, as always, let’s not jump straight into coding first. Time to review the task and algorithm first!

As a reminder, here is where we left our robot in Lesson 4, where it navigates to its favourite bottle of Ribena drink.

Robot navigates to its Ribena

Now, take out a pen and a paper (or digital equivalent), or even post-it notes (or equivalent).

Now, I would like you to think about writing the main part of the program to be as high-level as possible.

To start, you might try to rethink your algorithm at a ‘top’ level. And try to write out the ‘story’ or ‘narrative’ of your program at a high level, so that even a non-computing teenager can understand.

Start by listing out all the steps/tasks that your program should perform, in plain English.

So, for example, you might have some steps like

  1. Read in robot name
  2. Assign an ID to robot

etc.

Refer to your existing code to remind yourself of what you implemented. You can discard any task that is no longer relevant, for example computing the location quadrant.

There is no need for too much detail in some of the tasks, for example, you can have a task that simply says “Get robot to navigate to where Ribena is”

Try this yourself first, then continue once you are ready.