Lesson 9
No Object is an Island
Chapter 3: Refactor your robot!
Create a RobotFactory class
It will be even better to just turn this set of robot initialiser functions into a coherent class whose one job is to create a new robot. We can call the class RobotFactory
(or RobotInitialiser
if you prefer).
You can start by defining the RobotFactory
class and turning all the functions into methods (remember to add self
as the first parameter to each method).
Initialise RobotFactory
Then, add a constructor __init__()
. I noticed that to initialise a robot, I will need a list of potential robot names. Rather than passing this around all the time, let us just have the list of robot names as an attribute (i.e. composition)! The RobotFactory
can then just access the names directly whenever it needs them!
Similarly, you could have other attributes like prev_id
and grid_size
. This will free you from having to pass these values each time you invoke the methods.
Remember to add self
when you use each of these attributes in your methods (e.g. self.grid_size
)
Update the methods
The next thing you could do is to rename your methods to be more concise. For example, I renamed initialise_robot()
to create_robot()
, generate_robot_name()
to generate_name()
(because we already know that this is a factory to create Robot
s), generate_random_position()
to generate_position()
(because we know that we are generating an initial position for the new robot), etc. If you want your users to only use a single public method create_robot()
and not the others, you can put an underscore in front of each to indicate that they are only meant for internal use (e.g. _generate_name()
, _generate_id()
).
Create multiple robots in one go
I also realised that I can actually just have a create_robots()
method (note plural) to create multiple robots in one go, rather than having the main program create robots one by one. This can help abstract out the for-loop in the main program, delegating that responsibility to RobotFactory
instead. You can allow users to define how many robots to create with a count
input argument.
Create a new RobotFactory
instance
Once you are done, update main.py
to import the class (from robot_init import RobotFactory
), and update your code to create a new RobotFactory
instance and call the create_robots()
method.
When you are done, remember to commit your latest changes to your repo.