Friday, November 02, 2007

ActionScript Getters and Setters

It's always nice when a programming language surprises you in a pleasant way. ActionScript 3 has get/set property syntax, very similar to C#:


public class Person implements IPerson
{
private var m_name:String;

public function get name():String
{
return m_name;
}

public function set name(value:String):void
{
m_name = value;
}
}

What was an even nicer surprise is that you can define properties in an ActionScript interface:


public interface IPerson
{
function get name():String;
function set name(value:String):void;
}

And then write code that makes it look like you're accessing the field of an inteface:


var person:IPerson = new Person();
person.name = "Michael";

Now if only we had this syntactic sugar in Java... 

4 comments:

Anonymous said...

Wow, thanks! Couldn't find this in the Adobe book. I like especially how you can code it as "get property" but access it as "myObj.property". Nice!

Борис said...

Sorry, I don't see any sugars here.
Java's JavaBeans conventions are as ugly as .NET/AS getters/setters.

Compare same things in Scala:

trait Person {
def name: String
def name_=(n: String): Unit
}

class PersonImpl extends Person {
var name = "anonymous" // implements both from above
}

That's kinda it. To be honest, I've never declared getters and setters in interfaces. I doubt if you ever gain from syntactic sugars if you design your application that way.

dannystaple said...

@Борис perhaps because I don't know scala like I do AS2, .net and Java, but would your example work when name becomes a property that has code behind it?

public function get Name() { return name; }

is quite trivial. But when that becomes:

public function get Name() { return prefix + internalItem.attributes.name(); }

I can not see how your scala example scales to that.

Anonymous said...

Sadly for me this is no sugar.
Java getter / setters are good.
C# properties are good.
This is something in between and makes the code looks horrible. I'm not using Actionscript properties.