Tuesday, September 06, 2011

Getters and Setters

I first encountered the C# way of creating getters and setters, I thought they were such a nice improvement over the Java way of creating methods to get and set data. When I moved onto ActionScript 3, I continued to use and appreciate them (as they worked similarly to C#). They facilitated development nicely, you could quickly create a class with a public member, and then refactor that member to get and set functions without breaking the code that was accessing that member. For example, say you had a member:
public var data:String;
You could re-write it:
public var _data:String;
public function get data():String { return _data; }
public function set data(value:String):void { _data = value; }
The Java way (in AS3) would be:
public var _data:String;
public function getData():String { return _data; }
public function setData(value:String):void { _data = value; }
Lately I've been more careful about how I use getters/setters for two reasons:

First, the way I've been using them more recently has been a problem. I've been putting more code than I should in the setters, code that results in other state changes for the object. Side effects make debugging fun. I know, I know, this is an easy one to fix. But I must say it is so tempting to do!

Second, an advantage of a setData() function over a set data() property is that when using an IDE like Flash Builder, when you want to find all the places you called setData(), that's easy. But when you try to find all the places where the set data() function is called, you end up seeing all the places both get and set functions are called. I'm not sure if there is an easy fix for that one. It'd be nice if Flash Builder had a preference where when you searched for references of a set function, it did not include uses of the get as well.