Home Tutorials Forums Articles Blogs Movies Library Employment Press

Go Back   ActionScript.org Forums > ActionScript Forums Group > ActionScript 3.0

Reply
 
Thread Tools Rating: Thread Rating: 1 votes, 5.00 average. Display Modes
Old 09-17-2010, 06:05 AM   #1
Stardog Champion
Registered User
 
Join Date: May 2009
Location: Tokyo, Japan
Posts: 6
Red face Public variables vs. private variables with getters and setters

Hi all.

I've been programming in AS3 for about a year or two now. I understand the basic difference between public and private variables, as well as how you can use getters and setters to essentially make private variables public (or even read-only). However, I would like to know if there is any particularly good reason not to use public variables in classes.

When I was first learning how to work with classes, I came across this sample class in the AS3 documentation:

ActionScript Code:
// Filename Plant.as package {   public class Plant {     // Define property names and types     private var _leafType:String;     private var _bloomSeason:String;     // Following line is constructor     // because it has the same name as the class     public function Plant(param_leafType:String, param_bloomSeason:String) {         // Assign passed values to properties when new Plant object is created         _leafType = param_leafType;         _bloomSeason = param_bloomSeason;     }     // Create methods to return property values, because best practice     // recommends against directly referencing a property of a class     public function get leafType():String {         return _leafType;     }     public function get bloomSeason():String {         return _bloomSeason;     }   } }

Notice how in the comments just before the getters, it says "Create methods to return property values, because best practice recommends against directly referencing a property of a class". Also notice that, rather than using setters (or public variables), the two properties are passed in as parameters in the constructor.

Now, I understand that using a getter with no setter can make a variable read-only, and using a setter allows for the class to perform a function on a variable's property as it is set--in fact, I've actually done so several times, and it can make for some very powerful classes.

But back when I was still learning how to write classes, once I'd read the comment in the above class, I had made a habit of never using public variables, instead opting to use private variables with getters and setters. But unless you need the functionality that a getter or setter provides, this is a royal pain, as I wind up bloating my code by creating functionality that already exists when using public variables.

So, here are my questions:

1. Why was the above class written by using parameters and private variables with getters instead of using public variables?

2. Why does "best practice" recommend against directly referencing a property of a class? Is there some kind of problem with doing otherwise, or is there another reason?

Anyway, I hope someone here can provide me with some insight.

Stardog.

Last edited by Stardog Champion; 09-17-2010 at 06:08 AM. Reason: Misspelled the thread title
Stardog Champion is offline   Reply With Quote
Old 09-17-2010, 06:29 AM   #2
vikram_billa
Actionscript is rocking
 
Join Date: Nov 2008
Location: Hyderbad, India
Posts: 185
Send a message via MSN to vikram_billa Send a message via Yahoo to vikram_billa Send a message via Skype™ to vikram_billa
Default

This is just best practice, off course you can use public variables in your class, and some times using public variables will reduce our labor work.
__________________
VIKRAM BILLA
vikram_billa is offline   Reply With Quote
Old 09-17-2010, 06:56 AM   #3
Stardog Champion
Registered User
 
Join Date: May 2009
Location: Tokyo, Japan
Posts: 6
Question

Quote:
Originally Posted by vikram_billa View Post
This is just best practice, off course you can use public variables in your class, and some times using public variables will reduce our labor work.
I hate to sound like a crank, but this doesn't really answer my question. Why is it "just best practice?" What is it about writing classes this way that makes it best practice? Does it make it easier to read? Does it make it run faster? Does it protect the variables from harm in some way?

Also, I was reading a bit more in the documentation, and I came across this in the docs for getters and setters:

Quote:
Getters [and setters] allow you to apply the principle of information hiding by letting you create a public interface for a private property. The advantage of information hiding is that the public interface remains the same even if the underlying implementation of the private property changes.
Now, I am fully aware that when using a getter or a setter, you can include extra functionality that changes the input/output within the class. For example, perhaps the variable "time" is a Number variable of total seconds elapsed, but the getter function converts it into a string with colons between hour, minute, and second values. Or perhaps a setter might apply some kind of calculation to a value before assigning that value to a variable.

So, here's the question: am I right in assuming that this is what the documentation means by "information hiding"? Also, if there is no need for that--i.e., the getter and setter functions do nothing more than return a value and set the value as-is--then why not just eliminate all the extra getter/setter code by using a public variable?
Stardog Champion is offline   Reply With Quote
Old 09-17-2010, 07:08 AM   #4
vikram_billa
Actionscript is rocking
 
Join Date: Nov 2008
Location: Hyderbad, India
Posts: 185
Send a message via MSN to vikram_billa Send a message via Yahoo to vikram_billa Send a message via Skype™ to vikram_billa
Default

Now you are in right track. using setter / and getter class you are not only just assign the value, but also you can extend the process /functionality by including extra code / functions in getter / setter function.

And you can control the read / write properties . But we will get some cases where getter / setter method will not give any special benefits, at that time we can directly create a public variable and we can directly access it from outside of the class.
__________________
VIKRAM BILLA
vikram_billa is offline   Reply With Quote
Old 09-17-2010, 08:10 AM   #5
maskedMan
Obfuscated Coder
 
maskedMan's Avatar
 
Join Date: Apr 2008
Posts: 1,571
Default

vikram_billa has the right idea. The reason it's considered "good practice" is so that you give yourself the freedom to change the implementation of how the variables are read or written to, and these implementations can differ in subclasses.

Additionally, if you like to use Interfaces you cannot declare a variable in an Interface. You can declare get/set functions, though!



There are times when you might *not* want to use get/set functions though. The most important time is when you need faster performance and you're in a loop. get/set are function calls, and therefore are very expensive compared to directly accessing a public variable.
__________________
http://www.scriptocalypse.com - It's not the end of the world. It's just Actionscript!

man.mask = mask_mc;
maskedMan is offline   Reply With Quote
Old 09-17-2010, 01:58 PM   #6
lordofduct
Senior Member
 
lordofduct's Avatar
 
Join Date: Feb 2008
Location: West Palm Beach, FL
Posts: 3,872
Default

This discussion was recently on kirupa as well (and got rather heated very quickly).



getter/setters are slower to execute, and take more time to write by hand, so many will probably wonder why it's "good practice".

Well that phrase "good practice" doesn't come with what it's qualifying... and that is it's "good OOP practice". It reinforces encapsulation of fields in a class (a field is a var declared directly on the class, may they be private or public). Why is this good? Cause it's one of the main principles of OOP (encapsulation), and it allow for robust organization, like maskedMan brought up.



You don't have to use it though. As I said it's slower to execute, and some may kick and scream about how efficiency is prime concern number one (cause hey, the average flasher isn't writing a 3d games engine, from scratch). But others will bitch right back that it's not so. It really just comes down to personal preference about what you're attempting to accomplish.

If you aren't exploiting the many uses of OOP (just writing classes isn't really using OOP to its potential), then you probably don't really care. But when Interfaces, inheritance, overrides, and polymorphic types come into play... well a bunch of big words get thrown around that seem like they're just there to confuse you and these stupid little things like "use a getter/setter" is what those big words are talking about.
__________________
www.lordofduct.com - come read my blog!

If you want to know how to program, take a math class, take a lot of math classes!
lordofduct is offline   Reply With Quote
Old 09-17-2010, 04:01 PM   #7
spooner
Registered User
 
Join Date: May 2008
Posts: 48
Default

Quote:
Originally Posted by lordofduct View Post
...
I want to +1 this post
spooner is offline   Reply With Quote
Old 09-17-2010, 10:03 PM   #8
tadster
tadster
 
tadster's Avatar
 
Join Date: Feb 2009
Location: Texas
Posts: 2,111
Default

ok, so I wanted to say this on the kirupa thread, but well...
Here is one case in which using getters and setters in a round about way can actually improve performance.

Say I have some Class object with properties named "middleX" and "middleY", and on some loop I need to get an object of the type... let's call it the middleXer Class, so on some loop I need to get a middleXer from some vector(array) and update its middleX and middleY properties:
ActionScript Code:
var aMiddleXer:middleXer; for (var i:int = 0; i < 1000; i++) {  aMiddleXer = mdxersVector[i] as middleXer;//perhaps they get removed somehow, so we check for null  if (aMiddleXer) {     aMiddleXer.middleX = aMiddleXer.middleX + 1;     aMiddleXer.middleY = aMiddleXer.middleY + 1;  } }

Now lets imagine our middleXer Class has many other properties as well, it also has many methods... all in all, middleXer.as is 17kb.
So, during the above loop there is a 17kb 'look-up' going on during casting as a middleXer...
Now, compare the above versus:
ActionScript Code:
var aMiddleXer:ICompleteXYComputations; for (var i:int = 0; i < 1000; i++) {  aMiddleXer = mdxersVector[i] as ICompleteXYComputations;  if (aMiddleXer) {     aMiddleXer.middleX = aMiddleXer.middleX + 1;     aMiddleXer.middleY = aMiddleXer.middleY + 1;  } }

ICompleteXYComputations (don't mind the name)
is an interface, it only has the basic things that middleXer will implement, really all we need from middleXer, in this loop, is to make sure it has middleX and Y properties.
So using the interface comes into play.
The only way to give an interface properties is by using getters and setters:
ActionScript Code:
package {    public interface ICompleteXYComputations    {        function get middleX():Number        function set middleX(toThis:Number):void       //etc...    } }

But now notice the performance benefit in this situation, middleXer.as is 17kb, but the interface is only like 2kb, so the for loop (the casting) is able to happen much faster.
And there we have it, a performance use for getters and setters... not trying to advertise antyhing, but my recent game uses this technique.


Other than that... the others sumed it all up already.
__________________
www.actiontad.com - ActionScript and JavaScript sitting in a tree...
tadster is offline   Reply With Quote
Old 09-24-2010, 07:37 AM   #9
Stardog Champion
Registered User
 
Join Date: May 2009
Location: Tokyo, Japan
Posts: 6
Cool

Much obliged--your answers are very helpful. Thanks!

FYI: the truth is, I find that most of the time I wind up altering some other part of the class (or at least the value being set) most of the time anyway (especially when setting Boolean values), so I end up having to use getters and setters anyway.

Thanks again for the help!

Blain Armstrong
Toride, Japan.
Stardog Champion is offline   Reply With Quote
Reply


Thread Tools
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 06:26 AM.

///
Follow actionscriptorg on Twitter

 


Powered by vBulletin® Version 3.8.5
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
Ad Management plugin by RedTyger
Copyright 2000-2013 ActionScript.org. All Rights Reserved.
Your use of this site is subject to our Privacy Policy and Terms of Use.