O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Methods to Examine and Modify an Object's State

Earlier we learned that it's good object-oriented practice to declare instance variables private, meaning that they cannot be read or modified by code outside of the class in which they are defined. Good object-oriented practice dictates that, rather than allow external code to modify instance variables directly, we should instead define instance methods for examining or changing an object's state.

For example, earlier, we gave our VirtualPet class an instance variable named currentCalories. The currentCalories variable conceptually describes the state of each pet's hunger. To allow external code to reduce the pet's hunger level, we could make currentCalories publicly accessible. External code could then set the pet's hunger state to any arbitrary value, as shown in the following code:

somePet.currentCalories = 5000;

The preceding approach, however, is flawed. If external code can modify currentCalories directly, then the VirtualPet class has no way to ensure that the value assigned to that variable is legal, or sensible. For example, external code might assign currentCalories 1000000, causing the pet to live for hundreds of years without getting hungry. Or external code might assign currentCalories a negative value, which might cause the program to malfunction.

To prevent these problems, we should declare currentCalories as private (as we did earlier in our VirtualPet class). Rather than allowing external code to modify currentCalories ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required