Lesson 9
No Object is an Island
Chapter 7: More classes for your robot!
Designing new classes
Ok, did you come up with any other potential objects?
The two obvious objects I can think of are Drink
and Grid
. Both are very physical, and you can imagine the robot interacting with both objects.
Now, think about how Robot
, Drink
and Grid
can interact with each other. I visualised a Robot
navigating around the cells in a Grid
, picking up a Drink
from a Grid
cell when there is one, checking that the Drink
is meant for the robot, and if so drinks it (and be merry).
Just from the above sentence, more concrete details about the classes start to emerge.
Drink
does not depend on other classes and is self-contained. The only small dependency is that it is linked to theRobot
, but we can sidestep that a bit and only store the robot’s id as a string.Grid
has a number of cells, and each cell can contain one or moreDrink
s. Probably good if you can add moreDrink
s to any cell on the grid at any point.Robot
can be placed on aGrid
at any point. It will have information about the grid (like the size), and will be able to interact with the cells in theGrid
(to pick up anyDrink
s).
With that in mind, I made an initial attempt at updating my class diagram with Drink
and Grid
added.
I’ve indicated the relationship between Robot
and Grid
, and Grid
and Drink
using a simple association. You can arguably represent Grid
and Robot
with the stronger aggregation relationship - but this is just a small technicality. Some designers might even add a relationship between Robot
and Drink
just based on the fact that the robot’s ID is referenced there, but I prefer to keep it simple and treat the ‘owner id’ as an independent label.
Grid
will have a cell
attribute (a dict
) that keeps track of a list of Drink
s at that cell
location. Robot
now also has a Grid
as its attribute. I have also removed the grid_size
arguments in many of Robot
‘s method since this can be now accessed directly via self.grid.size
. I have also changed the semantics so that the Robot
‘s goal is now to nagivate_to_drink()
rather than to a specific cell position.
What I have just described is part of an Object-Oriented Analysis and Design (OOAD) process. We will not go into too much detail about this, but this would be how one would design an object-oriented software based on user requirements.