Chapter 8. Doing the Chores: set and get

Table of Contents
8.1. Get and Set Methods
8.2. Using Set Methods During Object Creation
8.3. Passing Information Around
8.4. Circumventing the Object-Oriented Guidelines

Object-oriented programming organizes the way programmers think about information in a new way. The objects maintain their variables (the "instance variables", or IVARs for short) and the information contained in those variables is private, self-contained within the object. This has benefits in the design of code and it also captures some intuitions the autonomy of individual agents in a simulation exercise.

Objects are thus insulated, more or less, and although this makes some things easier to code, it also makes some things more difficult. For example, in C a variable can be set and its value can be changed anywhere in the program. In object-oriented languages like Objective-C, an object can hold several variables and those values can only be changed by the object itself if we remain within the recommended limits of good programming habits. Some ways to go outside those bounds will be discussed below, but generally speaking it is a good idea to respect the fact that objects maintain their own data.

If objects are maintaining their own data, how do we manage information in a Swarm project. Early on in the development of Swarm, the coders adopted a convention (common to Objective C, Java, Smalltalk and numerous other object-oriented languages) that the term set starts a method name that sets a value inside an object, such as setIdealTemperature or setAge. The term get is used as the beginning of a method that causes the agent to return some value, such as getIdealTemperature or getAge.

8.1. Get and Set Methods

Get and set methods are needed to pass information among objects. For example, consider Heatbugs. In the Heatbug.m code, one finds a methods that set information inside the bug and also methods that retrieve information from it. Consider the method setIdealTemperature

 
- setIdealTemperature: (HeatValue)i
{
  idealTemperature = i;
  return self;
}

The Heatbug object has an instance variable called idealTemperature, and this sets the value of that variable.

If some other object needs to know the heatbug's ideal temperature, what has to be done? We would have to add a method to the Heatbug.m that returns the value of idealTemperature. Something like this might suffice:

- (double) getIdealTemperature
{
  return idealTemperature;
}

As much as possible, it is recommended that information be exchanged in this way. Hence, when the observer swarm needs a list of all the agents in a simulation in order to create a graph, the model swarm should have a method, such as getAgentList, that returns a list of agents that the observer swarm can use.