AS3 101: Five Reasons to use Setters and Getters
Tutorial Details
- Difficulty: Basix
- Platform: Flash Player 9+
- Language: AS3
- Software used: Any AS3 compiler
- Estimated Completion Time: 5 mins
Of course you know about setters and getters, who doesn’t? (If that’s you, you might want to brush up on Object-Oriented Programming with my Introduction to OOP tutorial). But why use them? Why go to the trouble of creating extra functions to wrap around a property? Here are five reasons that are incredibly useful.
Personally, I use each of these reasons at least once a day..
Reason 1: You can create read-only (or write-only) properties
By making the actual property private, and writing just a public getter (with no matching setter), you can provide access to reading the value, but disallowing changing the value from outside the class. This is useful for Immutable Value Objects that carry a bunch of data, but should never be changed once created. That, and around 500 other reasons to use read-only properties.
Reason 2: You can perform validation and auto-correct incoming values
Numeric properties oftentimes require a number between a certain set of values, or that is rounded to a certain precision. You can do this limiting or rounding in the setter to ensure clean values, or, if required, you could do this processing “on the fly” in the getter, in order to store a full-precision value internally, but provide a clean value to the outside.
Similarly you can provide default values or handle null values with a bit of logic. Suppose you have a Person object, with firstName and lastName properties. Let’s say that the business logic of the application dictates that these properties cannot be null. They can be empty Strings, but they can’t be null (because, oh, let’s say we’ll be running some regular expression searches on them and it would just be a lot easier to be certain that the String exists, rather than always checking for null).
So, in your setter, you might have something like this:
public function set firstName(s:String):void {
if (!s) s = "";
_firstName = s;
}
If you’re thinking that you could accomplish this with default values on arguments, then you should look up compiler error #1123: “A setter definition cannot have optional parameters.”
Reason 3: You can synthesize data
Imagine that same Person object from the last reason, with its firstName and lastName properties. To also implement a fullName property, you could create an actual property, and make sure you update fullName every time you set the firstName and/or lastName properties. Or you could simply create a fullName getter that returns an automatic concatenation of the first and last names:
public function get fullName():String {
return firstName + " " + lastName;
}
Reason 4: You can hide more significant logic behind a simple property
You could have a Button class that encapsulates a Sprite and handles much of the interactivity. An “active” setter could take a simple Boolean value and turn it into more complex logic that adds or removes event listeners, enables or disables the hand cursor, and turns on or off the mouseEnabled property of the Sprite.
Reason 5: You can instigate visual changes from a property change
This follows along from the last reason. What if you had Slider object, that was represented on-screen by, you know, a slider interface element. Suppose this object has a “value” property. By implementing a setter for the value, you can not only set the actual property to that number, but you can then also update the visual elements necessary to make the slider’s drag handle move to the appropriate position.
As a bonus feature, implementing it this way would also allow you to use a tweening engine on the Slider object, and tween the value. Most tweening engines allow you to tween any numeric property on any object, even properties that are really setters and getters.

Reason 6: By using getters and setters, you can have a tweening engine animate that property.
Reason 1 for NOT using getters and setters: They are slower than function calls and public variables.
Couldn’t agree more. Getters and setters are powerful things and make Object Oriented Programming that much sweeter :D
Another reason: setters & getters allows you to easily debug your application. Say you have a value changed and you’re not sure who changed the data you can put a line breakpoint and use the debug view in Eclipse to watch the changes. I highly recommend using them on all properties in a models class when using Micro architecture frameworks.
Love the series! Even though I consider myself to be an intermediate-advanced AS3 coder, I still find these incredibly fun and useful.
That said, when’s the AS3 201 series coming? :D
Definitely need to reiterate that they are slower to write and to run in code. If you aren’t using them for debugging, running extra logic, or protecting a variable DON’T use getters/setters.
:)
Reason 4: You can hide more significant logic behind a simple property
Having a logic with side-effects inside your setter is a great way to make your project messy and incomprehensible. It’s an anti-pattern. Believe me you better never do this.
You should take a look at this: http://jacksondunstan.com/articles/433 . Pay attention to the second and fourth result – getters/setters are almost 5 times slower that the public variable. Just making a function “getName()” would be faster than “get name()”. Personally I think as3′s special getters/setters should be avoided.
In my Java introduction course I was taught to keep logic outside of setters or getters, and to use these just for handling the property values themselves; setter for saving a value that is result of logic in the method, getter for feeding a value into the logic, and so on. Perhaps this was wrong?
I never use constructions like this:
public function set someStuff(value:Number):void
public function get someStuff():Number
They do not always work as they’re supposed to.
I use something like this instead:
public function setSomeStuff(value:Number):void
public function getSomeStuff():Number
These work much better and are more predictable
Also, the First Reason (read Only variables) is not completeley true.
AS3 is returning a reference(!) to complex classes (not int, Number, String, etc), so in your getters you are not returning the value, your are returning a reference, which can be used to change the original value.
Even more, that reference is preventing GC…
If you want a real “read only” you must make a copy of your variable and return that.
I disagree. Generally, if you’re using Accessors and Mutators, I don’t think you understand OOP.
Accessors and Mutators go against OOP because they break encapsulation, the very foundation of OOP. I don’t know exactly the adage coined on this topic but it goes something like:
‘code lives with data’
If you are having one object reach into another object to access some values, and then compute on those values – you’re doing it all wrong.
If your working with state – that’s a little different because you’re probably working with application architecture whereby state is shared.
Of course we need to be pragmatic on the issue, but generally this is bad.
i guess this is about flash and not about OOP :)
OOP is nice idea, but not working well in flash … getters and setters are horribly slow, they are so slow that it’s better to forget them completely, today the best way in flash is to use public properties, when you do not need directly the getter/setter functionality (tweening)
(in case somebody don’t understand what i am pointing at, try to find how many bodies can count flash version of box2d and how many bodies can make the alchemy ported version)
if you need as3 you need to do it very very lightweight … it means you can use getters/setters everywhere on really simple project
Thanks I do agree that this is a FANTASTIC series of Tuts on AS3.
I am a newbie and REALLY struggling with AS3.
Two Points:
Firstly WHY is it that although there are some GREAT Tutorials out there and even though some explain class structures VERY well (yours included) NOT ONE of the tutorials on classes explain how to use more than the Document Class in a project.
OK so we have the Project.fla and it calls the Main.as Class but we also have some code in a Second.as Class file. So HOW do we make the Main.as class talk to the Second.as class and the Second.as class talk to the Main.as class ????
Believe me theres a LOT of confusion out there amoungst newbies on this one. Maybe its OBVIOUS to you guys ???
Someone PLEASE PLEASE PLEASE show us HOW in an easy to understand tut.
Now after MUCH experimenting I have figured out how to do this (not sure why the method works – its just a few lines of meaningless code to me – but it does).
Now I am STRUGGLING to make the two classes read variables from one another. I heard somewhere that Getters and Setters can do this. After a LONG search found this post but SADLY it doesnt really show me how to implement Getters and Setters to pass variables between classes. You had a reference to the OOP tutorial but this just explains classes and I see no sign of any Getters or Setters (unless I missed something).
I come from an AS2 background but never heard the term Getter or Setter – maybe thats strange to you but its the truth. Maybe I was using them without realising it. In AS2 you simply called a variable _global and all could see it. I know thats NOT posible in AS3 so HOW do we do it ???
Thanks.
Paul
Having said that I see theres something in the Tut “OOP Additinal Concepts”.
So lets hope this answers my question.
Thanks
Paul