Getter/Setter best practices

In the german flashforum.de, there was a recent discussion about getters and setters. Some of the developers always use getter and setter-methods instead of just using public variables. They believe it’s good OOP-practice.
In my opinion, everybody can do what he/she wants to do, but should always keep something in mind: speed.

Since the moste ActionScripting is done for the Flash Player rather than other applications, we need to keep track of speed. The AVM itself can be very very fast. What’s slowing down there is the FP (my very own experience).

So, OK you want to use get/set because of good OOP or the advanced ASDoc functionality for it – that’s fine! But don’t tell me your code is slow! NAARP… :)

I really wanted to know, if there are any losings in performance when using getters and setters instead of public variables, or the other way around.
Yes, there are losings! In my tests, reading public variables was almost 3 times faster than doing the same with getter-methods. But writing a public variable was more than 4 times faster than writing via setter. I didn’t think that it would be that huge difference…

So my best practices for using getters/setters:
Use getters only if
1. Your getter returns more than only the requested value, e. g. you have a getter to read the full name and it will give you a String of firstName +’ ‘+ lastName.
2. You want a property to be read-only (only makes sense, if you’re creating an API for other developers, because you should know your own code ;)).

Use setters only if
1. You want to validate the given value.
2. When a property is changed, something else needs to be changed too, e. g. you change the labelString of a button, so the TextField’s text of that button should change accordingly.

You may want to download my test-case and share your results: BenchmarkTests

Comments (1)

  1. 12:54, 31. January 2013Etherlord  / Reply

    I never use get/set keywords, instead I create methods like setNick() and getNick(). That way I distinguish them from public properties without logic. It’s a terrible practice to make a heavy getter, as library users may not be aware they should cache the return value.

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Pingbacks (0)

› No pingbacks yet.