8.4. Circumventing the Object-Oriented Guidelines

If one wants to avoid treating objects as containers that hold both data and methods, one can do so. The C language allows the creation of global variables, ones that can be accessed in any part of the code. These external variables exist outside a particular class and are thus available to it. The names used for external variables must be unique. One cannot have a global variable called temperature as well as a temperature variable defined as an instance variable for each object. There are some occasions in which a program can be made to run more quickly if the whole get/set exercise is circumvented by creating a global variable.

Another way in which the object-oriented guidelines can be circumvented is the use of the -> operator. Suppose we have an object called dog and it has instance variables numberOfBones and timeSpentSleeping. Ordinarily, within the object-oriented paradigm, the numberOfBones would have to be set by a method such as setNumberOfBones. However, the language does allow a shortcut of the following sort. The syntax dog->numberOfBones refers to the value of the instance variable numberOfBones inside the object named dog. Hence, one could have a statement:

dog->numberOfBones = 3;

that sets the numberOfBones to 3 inside the dog. This kind of code is considered to be heavy-handed and brutish because it does not use the methods written for the dog class with which it can set that value and update it. A mistake made with the -> operator can corrupt the values inside an object.

Even though the usage of -> is discouraged, one does find examples of this syntax in Swarm code. Almost all Swarm examples use this kind of shortcut in the createBegin phase of the model swarm file, for example. This is done, however, because there is no alternative. We want the GUI probe display to allow the user to adjust parameter values before the simulation commences. It is thus necessary to set values inside some objects even before those objects have finished their createBegin/createEnd routine.