7.5. Variations on a Theme

Once you have seen how an object can be created, you should start thinking about how your simulation will be organized. Within the standard Swarm approach, you begin with main.m allocating space for the top level swarm, which may be either a gui or batch swarm. Then the model swarm object is created in that top level, and the model swarm in turn creates the substantively important objects that embody the model you seek to investigate.

There are a number of different ways in which the creation of objects can be managed. Some are more intuitive than others, some are more "reusable" than others. Since the first Swarm exercise for most people involves bugs, it is not surprising that many examples of Swarm code follow the convention of the bugs project. As found in SimpleSwarmBug3, for example, the ModelSwarm.m file creates the bug objects in this way:

- buildObjects
{
  Bug *aBug;
  int x, y;
  [some lines omitted here]
  bugList = [List create: self];

  for (y = 0; y < worldYSize; y++)
    for (x = 0; x < worldXSize; x++) 
     if ([uniformDblRand getDoubleWithMin: 0.0 withMax: 1.0] < bugDensity)
      {
      aBug = [Bug createBegin: self];
      [aBug setWorld: world Food: food];
      aBug = [aBug createEnd];
      [aBug setX: x Y: y];
  
      [bugList addLast: aBug];
      }
  
  reportBug = [bugList removeFirst];
  [bugList addFirst: reportBug];  
  return self;
}

This code cycles over the spaces in a lattice, and if the conditions are right, it causes the Bug class to create an instance of itself, called aBug, and then that instance is added to the bugList.

Some changes can be made to make this code a little more versatile. For example, create a new method called spawnOneBug that moves out the bug creation steps.

- buildObjects
{
  Bug *aBug;
  int x, y;
  [some lines omitted here]  
  bugList = [List create: self];

  for (y = 0; y < worldYSize; y++)
  for (x = 0; x < worldXSize; x++) 
  if ([uniformDblRand getDoubleWithMin: 0.0 withMax: 1.0] < bugDensity)
   {
    [self spawnOneBug];
   }
  
  reportBug = [bugList removeFirst];
  [bugList addFirst: reportBug];  
  return self;
}

- spawnOneBug
{

  aBug = [Bug createBegin: self];
  [aBug setWorld: world Food: food];
  aBug = [aBug createEnd];
  [aBug setX: x Y: y];
  [bugList addLast: aBug];

  return self;
}

Why is this more versatile? By isolating the steps necessary to create a bug and add it to the bugList in the spawnOneBug method, we make it much easier to add new bugs to the simulation as time goes by.