PDA

View Full Version : [AS3] Discussion on getters/setters etc



Shaedo
January 14th, 2010, 08:32 PM
Hi this is forked from this thread in order to avoid hijacking:
http://www.kirupa.com/forum/showthread.php?t=342018

I just want to start by saying that I respect that people can get emotional about this and have strong opinions and I personally hope that I don't offend anyone by stating mine. I am also always open to changing my opinion but I expect a very strong argument first! :)


I'd like to respond to Shaedo's comments regarding getter/setter methods. While you will find some programmers that do not like doing this, they are usually from a school of thought separate from OOP (object oriented programming) methodology.

Actionscript 3 is an OOP language in the purest sense of the word. When developing Flash applications you will make your life considerably easier to work with a strict OOP approach yourself. At the core of this methodology is the concept of compartmentalizing.

Using getter/setter methods maintains the consistency of this approach guaranteeing that only code within a class can read/write that class's vars.



@ Thinker2501 fair enough. I respect your opinion but I disagree on a few things:
"Actionscript 3 is an OOP language in the purest sense of the word." Personally I would say no more so than say JAVA, it has elements like classes etc and lends itself very well to OOP but you can write it in a purely procedural fashion which I think people that code purely on the main time line predominantly do, and I would not be surprised if that is the majority of people that code in AS3 (designers etc). (although I have no especial knowledge of how the distribution of AS3 codes apply their techinques)

"you will make your life considerably easier to work with a strict OOP approach yourself." yes and no, I personally would say to people learn and understand and where possible apply OOP when coding AS3 for flash but don't be limited by it. If you do enough coding you will encounter situations where procedural coding makes more sense, in particular when you are not coding in objects.

"Using getter/setter methods maintains the consistency of this approach guaranteeing that only code within a class can read/write that class's vars." Sure I acknowledge that many top level programmers have this view but personally I think that if you have a function like a getter or a setter then really you are simply creating an alternate method of externally changing a var, in effect making it public whilst declaring it private.

That all said I do agree that your arguments make sense and I do agree that they are true and valid points. for example "At the core of this methodology is the concept of compartmentalizing" is I think quite true and applicable to this situation.

So personally I see getters and setters as a slower method of achieving the same result and will (probably) never use them as such.

_kp
January 15th, 2010, 06:50 AM
In my opinion it doesn't matter if getter/setter methods are used or not, as long as their (non) usage is consistent. Well here comes the problem: Is it possible to use/not use them and still preserve consistency?

Inconsistency is just bad. If you look at a class with some getters/setters and some public variables without knowing it's internal behaviour, you need to guess how to access those values.
I don't want to remember weathers it is .size, .size() or .getSize() and maybe still get an error in the next step because the .size property is read only.

On "Actionscript 3 is an OOP language in the purest sense of the word" I must disagree too. It may can be used as pure OOP language but this whole timeline/frame concept doesn't fit in there. OOP in general will make life easier if used in the right places. but that's just part of being an OOP programmer: knowing when to use it and when not to.

dr_tchock
January 15th, 2010, 08:45 AM
I only use getters/setters if I wish to execute some other code when changing the value of a variable, otherwise I just use public vars. This might be "wrong" in strict OOP practises but it's a method that works for me.

Krilnon
January 15th, 2010, 11:05 AM
I think it's a little less awkward to call them accessors or accessor methods, since that's what a lot of other languages call similar constructs.

rumblesushi
January 15th, 2010, 11:15 AM
Personally I think they are completely pointless, especially for real time code. Maybe they could serve a good purpose for periodic interaction, but I see them being used to update variables in realtime.

The idea of using a function call to update a variable to me is insane, but I'm coming from a pure performance point of view.

wvxvw
January 15th, 2010, 11:54 AM
You cannot have a property in the interface and you cannot watch the modification made to the property if it's not a setter and you cannot prevent writing into the property if it's supposed to be read only if it's not a getter, sometimes this is a good enough reason to make it a setter / getter.
From another point of view, getters / setters aren't convenient because you cannot pass a reference to them to another objects, so, maybe sometimes functional style could be better... don't know...

claudio
January 15th, 2010, 11:59 AM
For small apps, exposing public properties within a class sounds just fine for me. Really guys, sometimes we just need to write functional code. But as the complexity of your apps increase, you can actually benefit from getters/setters, specially if you ever need to:

change the behavior of those accessors.
perform some validation before getting/setting the data.
log access to the property, by placing some logging code inside the getter/setter.
have different access rules for getter and setter eg. a public getter and a private setter. I don't know about AS3, but that's ok in C#.

Eppiox
January 16th, 2010, 07:04 AM
There should be a build in method to make our lives easier much like for a pixel by pixel hit test and other common problems people run into.
I could figure out AS2 code no problems but understanding AS3 takes me about 10x as longer and i have done java for 2 years now, similar but painstakingly slow.

Consistency matters but not if it's a small project and you can figure it out.

I find my self torn between doing things the "right" way but honestly if it works then there is not right or wrong, just a way with advantages and disadvantages associated with it.

dandylion13
January 16th, 2010, 10:34 AM
Getters/setters are only useful if they validate data or dispatch change events. If not, just keep your properties public. This is fine, no matter the scale of the project. There's no evidence to the contrary.

"Good OOP" and "doing things the right way" is a very complex, divisive and ultimately subjective issue.
You've seen this thread? It thrashes out the issues quite well and there some good links to articles on the subject:

http://www.kirupa.com/forum/showthread.php?t=340006

Voetsjoeba
January 16th, 2010, 10:50 AM
Getters/setters are only useful if they validate data or dispatch change events. If not, just keep your properties public. This is fine, no matter the scale of the project. There's no evidence to the contrary.

"Good OOP" and "doing things the right way" is a very complex, divisive and ultimately subjective issue.
You've seen this thread? It thrashes out the issues quite well and there some good links to articles on the subject:

http://www.kirupa.com/forum/showthread.php?t=340006

Yes there is, actually. It's fine to use public properties if your code will never change. Unfortunately, we all know that that is rarely the case, if ever. Therefore, I believe it is best to use getters and setters; even if you don't really need them right now, you might later - and when you do, you will be thankful to yourself that you used setters and getters so that you don't have to go scout all over your application to find where you used the properties you want to change.

rumblesushi
January 16th, 2010, 11:19 AM
You won't be thankful when your code runs far slower than it would with public variables though, due to the excessive amount of functions calls introduced by the getters and setters.

justkevin
January 16th, 2010, 11:58 AM
Yes there is, actually. It's fine to use public properties if your code will never change. Unfortunately, we all know that that is rarely the case, if ever. Therefore, I believe it is best to use getters and setters; even if you don't really need them right now, you might later - and when you do, you will be thankful to yourself that you used setters and getters so that you don't have to go scout all over your application to find where you used the properties you want to change.

An advantage of AS3's getter/setter model is that the external interface doesn't change if you switch between accessors and public. So you can use public properties. If you later decide that you need to: validate data, change internal states, dispatch events, calculate the value dynamically, etc., you can just add the public accessors.



public var center:Point;
Becomes:



private var _center:Point;

public function set center(p:Point):void
{
_center.x = p.x;
_center.y = p.y;
// Other stuff happens here
}
public function get center():Point
{
return _center;
}


Nothing else outside the class needs to change.

Voetsjoeba
January 16th, 2010, 10:33 PM
...

Yes, for languages that support that kind of setters/getters that would be correct. However, my point was meant as a more general remark and did not only apply to AS3.


You won't be thankful when your code runs far slower than it would with public variables though, due to the excessive amount of functions calls introduced by the getters and setters.

Got any stats to back that claim up? It depends on the language and runtime you're using of course, but compilers tend to be pretty smart - I'd be surprised if they weren't able to recognize "useless" setters and getters and bypass the extra function call alltogether at compile time.

Edit: I looked this up, and apparently the .NET compiler does this. The Hotspot JVM will also eventually inline the call after having been called enough times.

Regardless, the benefits of adhering to proper OO principles and having code that can be easily maintained are usually considered to far outweigh the performance hit (if any).

dandylion13
January 16th, 2010, 10:49 PM
Got any stats to back that claim up?

He does, he's coded the fastest AS3.0 3D engine on the planet ;) Check the Games/A.I forum.

Voetsjoeba, My code changes all the time but using public properties has never been a hindrance.

Could you give us some evidence to support your claim that using public properties prevents future changes?

Voetsjoeba
January 16th, 2010, 11:07 PM
He does, he's coded the fastest AS3.0 3D engine on the planet ;) Check the Games/A.I forum.

Right, then I suppose the AS3 runtime and/or compiler does not optimize getters and setters the way other environments do. Yes, in that case, since performance is absolutely critical would suffer unacceptably otherwise, using public properties is a good idea. That's just common sense. However, I do maintain that for applications where doing so does not kill your application, public properties should be avoided where possible (-:


Could you give us some evidence to support your claim that using public properties prevents future changes?

I'm not saying that using public properties prevents future changes, I'm saying that you'll have a much harder time if you're not using getters and setters (provided your language has not already foreseen this and uses the same syntax for getter/setter invocation and direct property access).

As for evidence of this, just find any book on the principles of OOP.

wvxvw
January 17th, 2010, 05:41 AM
Well, there are situations where you cannot do without getters/setters, like if you ware to design an MXML template - then it simply has no way of calling functions, so, your only option would be to have setters and getters. (You cannot do away with properties because you cannot make them bindable). I do realize that MXML templates are the sloppiest code ever, but, sometimes you can live with that so far the performance isn't an issue.
I think I myself overuse getters/setters, and if I would give it more thinking, I'd rather design them as a getting and setting functions - it is easier to deal with + it sort of allows you to pass a reference to the class field (which is otherwise impossible in AS3). However, since I'm porting myself to HaXe, I sort of don't have to deal with that problem any more, because of how properties are designed there.
I think that one of the benefits of OO approach is in making the code more reliable by having more "against fool" protection, that would be the case with properties... But, TBH, this protection may look simply ridiculous some times.

dandylion13
January 17th, 2010, 10:46 AM
Hmm... I'm not convinced guys :)

To me, this seems like sheer madness:

public function get property():Type
{
return _privateProperty;
}

Yet it appears to be widely practised?

Again, if anyone can give me some hard facts why this is good OOP, I'm all ears.

Really, I just want to learn, I'm not trying to be difficult ;)

wvxvw
January 17th, 2010, 10:56 AM
If you have:

public interface IFoo
{
function get property():Type;
}
That's the best you can do.

rumblesushi
January 17th, 2010, 11:10 AM
Right, then I suppose the AS3 runtime and/or compiler does not optimize getters and setters the way other environments do. Yes, in that case, since performance is absolutely critical would suffer unacceptably otherwise, using public properties is a good idea. That's just common sense. However, I do maintain that for applications where doing so does not kill your application, public properties should be avoided where possible (-:



I'm not saying that using public properties prevents future changes, I'm saying that you'll have a much harder time if you're not using getters and setters (provided your language has not already foreseen this and uses the same syntax for getter/setter invocation and direct property access).

As for evidence of this, just find any book on the principles of OOP.

That's right, the AS3 compiler doesn't do anything to streamline your code, excessive function calls increase the stack by a lot. And yes getters and setters are left as function calls.

I'd just like to clarify, as I stated before, I'm coming at this from a pure performance angle. I benchmark almost every addition or change in code I make, because in a browser based software renderer, performance is paramount. Yes far more important than adhering to "proper" OOP principles. I'll also try to do the same thing several ways, to see which is faster, not just what works.

Somebody can adhere to proper OOP principles all day, it's not exactly hard, it doesn't make them a good programmer, and it doesn't mean their work is of any real value.

I'm working on a big, complicated project at the moment, structured 100% OOP of course. I haven't found one instance where I actually need a getter or setter. If I need a condition to control or regulate this variable as a getter or setter might be used for, I'll include it somewhere else in the pipeline, to save on the function call.

Now there might be some projects where getters and setters are absolutely necessary, as wvxwv alluded to.

But most of the time they're not.

To put it simply, for code that's running every frame, variables that are being updated every frame, don't use getters and setters. You should be aiming to reduce function calls, not increase them. For periodic interaction or certain single events, then use getters and setters if you so desire.

Also - after speaking to proper console devs, they care more about results, not OOP principles.

Websites and games alike are judged on the end result, and the appeal and functionality to the end user, not how well they adhere to OOP principles.

Voetsjoeba
January 17th, 2010, 12:00 PM
Somebody can adhere to proper OOP principles all day, it's not exactly hard, it doesn't make them a good programmer, and it doesn't mean their work is of any real value.

I'm working on a big, complicated project at the moment, structured 100% OOP of course. I haven't found one instance where I actually need a getter or setter. If I need a condition to control or regulate this variable as a getter or setter might be used for, I'll include it somewhere else in the pipeline, to save on the function call.

Now there might be some projects where getters and setters are absolutely necessary, as wvxwv alluded to.

But most of the time they're not.

Also - after speaking to proper console devs, they care more about results, not OOP principles.

Websites and games alike are judged on the end result, and the appeal and functionality to the end user, not how well they adhere to OOP principles.

You're still coming at this purely from a performance perspective, though. I agree with what you're saying, but only when applied to applications of the kind you appear to be working on, i.e. where every single additional stack frame is a potential show-stopper. I'm talking more about the general field of software development with projects ranging from small utilities to full-blown systems developed by several separate teams in parallel.

What I'm trying to convey is that you should use getters and setters when it makes sense, which by default is always. You just happen to be in the middle of a case where it doesn't, but that shouldn't lead to the conclusion that they shouldn't be used.


I haven't found one instance where I actually need a getter or setter

Funny you should mention that. This is exactly the point; you usually don't need them right now, but you do later when changes are inevitably introduced. The whole point of getters and setters is to minimize maintenance effort, which will always be a prospective measure. As you move from projects developed by one or a few developers to entire teams dedicated to single modules, you'll find your maintenance efforts and costs skyrocket if you scatter public properties all over the place.

Sure, there will always be the odd project where no changes are introduced, or projects small enough for changes to be trivially made, and you could argue that for such projects public properties are an acceptable choice. I, however, believe that you should always write code with best practices in mind, regardless of the project size you're working on. Who knows, the small project you're writing today might one day turn into a big one.

wvxvw
January 17th, 2010, 03:04 PM
If I'm allowed to make this broad approximation, I'd say that OO principles are all about "against fool protection". They weren't intended for performance optimization, however, they make the development process easier.
I will make another broad approximation here if I'd say that the abilities of programmers are often underrated by this approach, besides, nowadays there are bunch of other things that stand guard against erroneous code. Like, compilers would check typing before compiling, IDEs would check it even before the compilers etc... Getters/setters are but another level of protection, however, given the circumstances, which is the FP runtime and AS3 compilers, using getters/setters seems to be a bit of a waste...
There are lots of things that we use not because we must, but because we're used to, or just have picked this practice in some unrelated circumstances... I think, if you've coded in AS2 you should remember the way keyboard listeners, for example, ware handled. I think it came from copying the manual blindly. It went something like this:

var listener:Object = { };
Key.addListener(listener);
listener.onKeyDown = function():Void { ... }
I'm sure I've seen hundreds of code snippets in tutorials of all kinds where for unknown reason people created this redundant listener object, when, what they needed in fact was the "this" or another "real" object that needed to respond to keyboard events.
This seems to be the case with getters and setters: even though the instances when you actually need them are few (like, when working against an interface, or being forced to not use functions), you'd still do it because... well, no explanation :) just because it looks smart and advanced :)

dandylion13
January 17th, 2010, 04:47 PM
Those are good observations, wvxvw.

I've also begun to suspect that blindly following "best practices", regardless of whether or they make any sense, has a lot to do with jostling for status in the coding-hierarchy.

caltrop
January 17th, 2010, 04:49 PM
Another goal of OOP is to make a structured method for writing code, not for your own benefit but to make it easier for other people to understand it. If you have ever tried to pick up someone's procedural project before, you will understand why such standards are helpful.

Also, if you are keeping your classes encapsulated, you shouldn't be writing many (if any) public getters/setters anyway. It sounds like some of you took a very small piece of the OOP model, declared it a waste of time, then never bothered to learn the rest of what makes the model work.

Getters and setters are only a waste of time if you are using them incorrectly.

rumblesushi
January 17th, 2010, 05:19 PM
You're still coming at this purely from a performance perspective, though. I agree with what you're saying, but only when applied to applications of the kind you appear to be working on, i.e. where every single additional stack frame is a potential show-stopper. I'm talking more about the general field of software development with projects ranging from small utilities to full-blown systems developed by several separate teams in parallel.

What I'm trying to convey is that you should use getters and setters when it makes sense, which by default is always. You just happen to be in the middle of a case where it doesn't, but that shouldn't lead to the conclusion that they shouldn't be used.



Funny you should mention that. This is exactly the point; you usually don't need them right now, but you do later when changes are inevitably introduced. The whole point of getters and setters is to minimize maintenance effort, which will always be a prospective measure. As you move from projects developed by one or a few developers to entire teams dedicated to single modules, you'll find your maintenance efforts and costs skyrocket if you scatter public properties all over the place.

Sure, there will always be the odd project where no changes are introduced, or projects small enough for changes to be trivially made, and you could argue that for such projects public properties are an acceptable choice. I, however, believe that you should always write code with best practices in mind, regardless of the project size you're working on. Who knows, the small project you're writing today might one day turn into a big one.

Could you give me an example of what kind of change might be introduced that would in turn require the use of a getter/setter?

In regards to best practices, well, I think code should be concise, even if it's not intended to be used by other developers. I'm sometimes confused by my own code if I haven't looked at it for a while and it's not concisely put together.

But I've talked to a couple of devs from major game studios, and they seem to prioritise performance over strict OOP principles or "best practices".

But that is videogames we're talking about, where even on powerful hardware like a 360 or PS3, every bit of juice counts to stay ahead of the game, and push the boundaries of what the machine is capable, just on a much larger scale than Flash. I don't have experience of other areas of software development.

Can you imagine though, the lead programmer makes some major changes to a 3D engine on an upcoming game, completely restructures the pipeline, gets it running at 60 frames a second rather than the 30 it was running at before - at the expense of a few best practices and OOP principles, presents it to his boss and the boss says "Sorry Bob, impressive as it is, you'll have to change it back, you've broken some of the golden rules of OOP, we'll stick with 30fps".

dandylion13
January 17th, 2010, 05:22 PM
Also, if you are keeping your classes encapsulated, you shouldn't be writing many (if any) public getters/setters anyway.

Data objects need to make their properties accessible to other objects.
This is the one (and maybe only) situation where using getters/setters or public properties is essential and there are no alternatives.

Also, we're not declaring getters/setters a waste of time. We're just figuring out the best way to use them.

If it were a simple issue, the best minds of Kirupa would not be contributing to this thread.

And we still don't seem to have a consensus (or even good answers to many of these questions) so I look forward to the debate continuing :)

rumblesushi
January 17th, 2010, 05:23 PM
Those are good observations, wvxvw.

I've also begun to suspect that blindly following "best practices", regardless of whether or they make any sense, has a lot to do with jostling for status in the coding-hierarchy.

Honestly, I agree. Not unlike people using Eclipse to make themselves feel like a proper programmer :D

wvxvw - Ha ;) Honestly, I always wondered what that was about, the dummy object to attach a listener to, I had no idea why people did it.

Voetsjoeba
January 17th, 2010, 06:09 PM
Could you give me an example of what kind of change might be introduced that would in turn require the use of a getter/setter?

I don't have a real-world example off the top of my head, but suppose you have an application that needs to calculate some statistics as part of its what it does. So you build the application not using getters and setters, and everything is fine and dandy. Then next year some sales guy decides that the statistics that are being calculated suck and need to be "bumped up" a notch (granted, this would probably constitute fraud, but from some stories I've read you can expect anything from sales guys to make their product look superior).

So now, some value needs to go +20k throughout the entire application. Who would have thought such a change to ever occur, right? Turns out that value is actually pretty central to the entire application - makes sense, since it would be an application-wide change. So if you're not using getters and setters, you get to revisit, say, ~1.5MLOC of last year's code for places where that value is being used and add +20k everywhere. Or, you could have used getters and setters from the get go and add +20k in a single location. Presto! You just saved yourself 3 weeks of agony.


Can you imagine though, the lead programmer makes some major changes to a 3D engine on an upcoming game, completely restructures the pipeline, gets it running at 60 frames a second rather than the 30 it was running at before - at the expense of a few best practices and OOP principles, presents it to his boss and the boss says "Sorry Bob, impressive as it is, you'll have to change it back, you've broken some of the golden rules of OOP, we'll stick with 30fps".

Actually, what is likely to happen is that the boss will evaluate the impact of those changes on future usage of the engine. If squeezing out every last drop of FPS comes at the cost of ending up with a horrible mess of an engine that nobody but that single developer can understand or maintain, then I can guarantee that the boss will go with the 30FPS version and keep a maintainable engine that can generate profits for years to come with comparatively little cost rather than go with the 60FPS version and risk spending way more time and money on creating future games using that engine. Can you imagine if that single developer decides to leave the company at some point?


Honestly, I agree. Not unlike people using Eclipse to make themselves feel like a proper programmer :D

Hey, I happen to love the crap out of Eclipse! :P Gotta love Ctrl+3.

dandylion13
January 17th, 2010, 06:34 PM
Thanks for that explanation Voetsjoeba, it makes sense to me :)
I guess we have an advantage with AS3.0 in that the getters/setters look exactly like public properties so this would be a minor change. No so in other languages.

Shaedo
January 17th, 2010, 06:41 PM
At this point I have to say I am agreeing with pretty much everything that rumblesushi is saying. I acknowledge this may very well be due to what I code for but I think it's more my style of keeping well documented, well commented, good OOP code. So if I want to change something that say adds '20k' units every time then I know exactly where and how it's called and (I would like to think) that other programmers can look at my code and also work it out easily enough.

Regardless of the types of apps I code (which range from games to content management systems to flash based interfaces for scientific equipment such as live cell imaging microscopes) I have never come across anything that comes under wvxvw's circumstances, although wvxvw is doubtlessly a more advanced programmer than I am.

@ Voetsjoeba Perhaps, for a real world example, you could give an example where you, yourself have benefited by using getters/setters ? Also I would like to say that I really appreciate your debating for the use of getters setters, even though it is not changing my opinion on their use yet, it's giving me something to think about, which is exactly what I wanted.

@ dandylion13 If you are waiting for a consensus then start knitting that house cover you always wanted :P

rumblesushi
January 17th, 2010, 07:06 PM
I don't have a real-world example off the top of my head, but suppose you have an application that needs to calculate some statistics as part of its what it does. So you build the application not using getters and setters, and everything is fine and dandy. Then next year some sales guy decides that the statistics that are being calculated suck and need to be "bumped up" a notch (granted, this would probably constitute fraud, but from some stories I've read you can expect anything from sales guys to make their product look superior).

So now, some value needs to go +20k throughout the entire application. Who would have thought such a change to ever occur, right? Turns out that value is actually pretty central to the entire application - makes sense, since it would be an application-wide change. So if you're not using getters and setters, you get to revisit, say, ~1.5MLOC of last year's code for places where that value is being used and add +20k everywhere. Or, you could have used getters and setters from the get go and add +20k in a single location. Presto! You just saved yourself 3 weeks of agony.



Actually, what is likely to happen is that the boss will evaluate the impact of those changes on future usage of the engine. If squeezing out every last drop of FPS comes at the cost of ending up with a horrible mess of an engine that nobody but that single developer can understand or maintain, then I can guarantee that the boss will go with the 30FPS version and keep a maintainable engine that can generate profits for years to come with comparatively little cost rather than go with the 60FPS version and risk spending way more time and money on creating future games using that engine. Can you imagine if that single developer decides to leave the company at some point?



Hey, I happen to love the crap out of Eclipse! :P Gotta love Ctrl+3.

Hey Voet, thanks for the example.

As it happens in the 3D engine I've built I have a stats class, that calculates the framerate, rendered polygons in the current frame, polygons per second, active models, active vertices, clipped polygons, etc.

It's a class with public static variables. All the other classes update stats, for example stats.renderedPolys++; etc. The stats class has a function that updates the textfields, and a 1000 ms interval that calculates the framerate and polys per second.

Now if I wanted to lie and exaggerate the performance of my engine, I could simply add renderedPolys *= 2 after the stats are totted up every frame, before the text fields are updated.

Do you not think it would be possible to engineer most apps to work like this, making things easily editable on a global scale without the need for getters and setters?

I think your example is based on updating or retrieving a value in many different objects right?

One could achieve the same effect by having one function that projects or retrieves this value into/out of however many objects, with the object just containing a public variable. Any alterations you want to make to the value can be made within the one loop, of just one function, instead of using getters/setters which would equate to an additional function call for every single object you have that you're updating or retrieving data from.

In regards to the game example I used, well obviously in this extreme example there is no doubt at all the honchos would pick the 30fps version if it was seen to be more "sustainable".

But I didn't say the code would be a horrible mess ;) Obviously nobody would want that. For other devs in the team the code would be perfectly legible, almost as legible as before, and the engine would be pretty much just as easy to update and tweak for next year's sequel. The only difference is that it takes a few shortcuts here and there, the code is streamlined, and it doesn't strictly adhere to OOP principles. I can almost guarantee you they would choose the faster version.

You could of course swap (30fps to 60fps) to doubling the polygon count at 30fps, which for most 3D games is probably more likely. The only games that tend to target 60fps these days are fighting games and racing games. Most studios would choose an increase in graphics and polygon count to an increase in framerate. Not me, me is the framerate whore ;)

wvxvw
January 17th, 2010, 07:21 PM
@Voetsjoeba:
Considering your example... well, even Eclipse nowadays can perform "Find all references" task, maybe not FlexBuilder, but, I think FlashBuilder does it... there's some stuff on refactoring they improved in the last version. VS could do this years ago too... As I'm coding in FD, I would either use a refactor plugin, or just search for ".propertyName =" and go through the code making changes... I'd say it's a crazy situation when you have the same property mentioned in the code hundred times (but, when you see this happens, you'd usually want to make it a configuration property or a constant defined only once... regardless of the coding style, if there are to many objects setting the same property, there's something wrong in a general approach, so, I wouldn't deem this situation a valid example), but even then the replacement would take me like an hour... Now, I wouldn't imagine this situation will happen on a day to day basis... it sounds rather a force-major...
On the other hand, I'm used to see Eclipse error stack traces on the daily basis, and when I see stuff like [99 more lines truncated ...] or something like that under the stack trace... well, you know what people think in situation like this :)
Flex framework isn't yet there, but it is attempting to copy from Java all the evil it can find there :) We used to call this an "Enterprise style" coding - don't know if this makes sense to anyone, but this was intended to be funny.

Voetsjoeba
January 17th, 2010, 08:10 PM
At this point I have to say I am agreeing with pretty much everything that rumblesushi is saying. I acknowledge this may very well be due to what I code for but I think it's more my style of keeping well documented, well commented, good OOP code. So if I want to change something that say adds '20k' units every time then I know exactly where and how it's called and (I would like to think) that other programmers can look at my code and also work it out easily enough.

How exactly would that work? Are you going to have each method's documentation list every single public property it uses from any object it happens to use? Good luck keeping that up, keeping that documentation consistent and finding other programmers willing to spend their time and efforts to join you in doing that. I guess the alternative would be to add comments in the method bodies themselves, in which case you've made no progress from no documentation at all since people are going to have to go through the entire thing anyway.

Furthermore, if you're going to write proper documentation anyway, why would you want to document the same use of public properties all over the place? Why wouldn't you use a getter instead and document that one?

Additionally, if you need to make changes to public properties, there's simply no way around duplicating the change all over the place. This is just plain code duplication, and it's bad for the same reasons an entire theory has been built on normalizing database schemes.

And finally, I haven't even touched on the subject of the risk of introducing additional bugs. The more places you need to change code, the more places you're likely to inadvertly break stuff. And if that happens, then you're in a whole new world of hurt because you'll need to go through the entire thing again looking for the place where it got bugged. And if it turns out the changes you've been making all over the place were really the cause of the bug instead of the code using it, then you get to do it a third time. And if then you forget to change it back in some place you've done it again. And so on, the pain never ends.



@ Voetsjoeba Perhaps, for a real world example, you could give an example where you, yourself have benefited by using getters/setters ? Also I would like to say that I really appreciate your debating for the use of getters setters, even though it is not changing my opinion on their use yet, it's giving me something to think about, which is exactly what I wanted.

Easy; if you've ever played around with video or image processing, you'll know that off-by-ones tend to occur and can be very hard to track down due to lots of math going on, and basically having to go back down to the gory numeric details of algorithms again to find the expression that's missing a +1 or -1.

This particular case was a video processing application. I had a class Frame that represented an entire video frame and was happily coding away at algorithms with it. A while later I noticed that having algorithms affect only particular areas of the frame was becoming a pain - lots of indices flying around, all very prone to off-by-ones. So I figured that a class representing a subframe within a proper Frame would come in handy to automatically limit the area of effect of some algorithms (let's call them FrameAreas), and at the same time avoid a large amount of the indexing mess, thus also reducing further potential for bugs.

Because I used getters and setters rather than public properties in the original Frame class, I was able to implement these subframes (FrameAreas) with literally no change to the algorithm code using it. All I had to do was make the getters virtual and override them to add an offset value. Consider the effort that would've been required if I hadn't used getters and the enormous amount of bug-potential that kind of changes would bring. And even though performance is pretty important to video processing, I still went with getters, and I was right to.

Also, I've been able to fix numerous bugs by fixing just the getters in these subframes, whereas I would've otherwise been required to go digging through entire algorithms again looking for where the properties were used.

rumblesushi
January 17th, 2010, 09:37 PM
How many times would you have needed to manually add the offset value, if you were just using public properties?

And in this video processing app, how many variables are read/updated each frame with getters/setters, or rather, how many times are variables read/updated each frame with getters/setters?

And in regards to digging through entire algorithms - I regularly change classes full of properties simultaneously, with "replace all" :D Which is probably what I would have done with your subframe class, when adding an offset value.

Voetsjoeba
January 17th, 2010, 09:47 PM
Do you not think it would be possible to engineer most apps to work like this, making things easily editable on a global scale without the need for getters and setters?

I think your example is based on updating or retrieving a value in many different objects right?

One could achieve the same effect by having one function that projects or retrieves this value into/out of however many objects, with the object just containing a public variable. Any alterations you want to make to the value can be made within the one loop, of just one function, instead of using getters/setters which would equate to an additional function call for every single object you have that you're updating or retrieving data from.

That's right, in my example the value being edited was meant as an example of a value that's used all over the place in multiple modules, serving as the basis for several other calculations.

If I understand you correctly, what you're proposing is the have a single function that sets a value for a property in all objects that have that property, and have all those objects expose it is as a public member? That pretty much limits your possibilities, doesn't it? Wouldn't that pretty much require you to maintain a bunch of functions for each property for each object with lists of objects that are affected by that property? That sounds like an absolute nightmare.

I was particularly thinking about having multiple graphs presenting those same statistics in various ways (graphs, charts, whatever) using MVC. I don't even think MVC is at all possible without setters, because without setters on the model there would be no way for them to know when their values have changed, or even to validate new incoming values. That also means views have no way of knowing when the model has been updated, thus effectively destroying the whole concept.


In regards to the game example I used, well obviously in this extreme example there is no doubt at all the honchos would pick the 30fps version if it was seen to be more "sustainable".

But I didn't say the code would be a horrible mess ;) Obviously nobody would want that. For other devs in the team the code would be perfectly legible, almost as legible as before, and the engine would be pretty much just as easy to update and tweak for next year's sequel. The only difference is that it takes a few shortcuts here and there, the code is streamlined, and it doesn't strictly adhere to OOP principles. I can almost guarantee you they would choose the faster version.

Well yes, in that case nobody in their right mind would stick to the 30FPS version. You're always going to have to balance maintainability against performance, though - my previous example was meant as an illustration of this. The more you make changes that improve performance, the more you're hurting maintainability and vice-versa. It's a fundamental trade-off, there's no way around it.

What can vary though, is the ratio by which they are related. In your 3D engine, for example, introducing even a little extra maintainability through getters and setters sets performance back unacceptably. In my example, the application will incur no performance hit to speak of. That's why I mentioned that you should use them whenever it makes sense. I think we can both agree that, if it's basically free, there is no sound reason not to use them, right?

Your point is valid as well and in fact further reinforces my point: game developers do tend to bias the balance towards performance, but they will never push it so far as to overly hurt maintainability. Because of the relative importance of performance they're willing to take a hit in modifiability, just as in my example you would be willing to take a performance hit for the increase in maintainability. It all depends on the relative importance of either in your application.

Voetsjoeba
January 17th, 2010, 09:58 PM
How many times would you have needed to manually add the offset value, if you were just using public properties?

And in this video processing app, how many variables are read/updated each frame with getters/setters, or rather, how many times are variables read/updated each frame with getters/setters?

And in regards to digging through entire algorithms - I regularly change classes full of properties simultaneously, with "replace all" :D Which is probably what I would have done with your subframe class, when adding an offset value.

Well I haven't actually gone and counted it :D You shouldn't even have to care how much places you have to change it in, every one above just one is one too many.

So what if at one point you wanted to use the same algorithm for both limited area of effect and full-frame? Further complicate the algorithm to take both into account? Then what if in the future some extra frame type comes along?

Find/replacing public properties is probably the worst possible way to perform maintenance. What if you change, say, value to value + 2*i, and a year later go back in with find/replace all and change value again but forgot you added the + 2*i and end up with value + foo + 2*i? Instant bug, instantly duplicated all over the place.

Basically what you'd be doing is coding your algorithm as a large switch statement for every possible implementation. This is universally recognized as bad practice. In the way I've illustrated above, you can use polymorphism to transparently apply the same algorithm in different contexts, and setters and getters are a natural part of that.

Shaedo
January 17th, 2010, 10:48 PM
How exactly would that work? Are you going to have each method's documentation list every single public property it uses from any object it happens to use? Good luck keeping that up, keeping that documentation consistent and finding other programmers willing to spend their time and efforts to join you in doing that. I guess the alternative would be to add comments in the method bodies themselves, in which case you've made no progress from no documentation at all since people are going to have to go through the entire thing anyway.

I think your criticism might be a bit extreme :P . By good documentation I mean that it is clear what classes, functions, important vars etc do, and how they interact. Combine this with good OOP (which I did say earlier) where the interaction and hierarchy between objects is clear and finding, what public var, to change where, is not so hard, at least in any of the code I have ever seen. Again maybe due to my limited experience. Please don't misunderstand where I am coming from; I am happy to acknowledge that in your case, possibly even in the majority of cases, getters and setters are a better way to go! :)


Furthermore, if you're going to write proper documentation anyway, why would you want to document the same use of public properties all over the place? Why wouldn't you use a getter instead and document that one?
For me documenting a getter/setter compared to documenting a public var is of no difference. In all circumstances there would be the same number of things you need to document, and depending on the layout of your code essentially in the same place (or close enough). Just looking at the code examples from the Adobe team and Senoculars' public code they document the vars in pretty much this method. (I am not claiming this is their standard way of coding but it is how they code their publicly accessible code).

wvxvw
January 18th, 2010, 03:16 AM
@Voetsjoeba:

I've written few file parsers or other similar stuff like complex serialization / deserialization algorithms, from what I know, video codecs are admittedly difficult to write, but they fall outside the scope of this discussion since writing one in AS3 would be a pure madness :) And, from my experience doing this - I never needed, not even once a getter or setter... Especially considering AS3 bad performance in this regard...
Well, you see, it's OK for the compilers that may inline your property or subroutine function to separate code like you suggest, but, again, since we are talking about AS3 compilers that cannot do inlining, it technically, leaves you with no option but do the inlining yourself. I would see how over-functional property access may be useful in the process, but not in the final product.

Voetsjoeba
January 18th, 2010, 07:19 AM
@Voetsjoeba:

I've written few file parsers or other similar stuff like complex serialization / deserialization algorithms, from what I know, video codecs are admittedly difficult to write, but they fall outside the scope of this discussion since writing one in AS3 would be a pure madness :)
And, from my experience doing this - I never needed, not even once a getter or setter... Especially considering AS3 bad performance in this regard...
Well, you see, it's OK for the compilers that may inline your property or subroutine function to separate code like you suggest, but, again, since we are talking about AS3 compilers that cannot do inlining, it technically, leaves you with no option but do the inlining yourself. I would see how over-functional property access may be useful in the process, but not in the final product.

I'm not talking about just AS3 here though, I'm talking about the entire field of software development regardless of language. As mentioned above, AS3 appears to be an exception to the general rule that getters and setters have little impact on performance, and you should adjust your decision whether to use them accordingly. That changes nothing to their usefulness though, and does not mean they shouldn't be used in general.

rumblesushi
January 18th, 2010, 10:31 AM
That's right, in my example the value being edited was meant as an example of a value that's used all over the place in multiple modules, serving as the basis for several other calculations.

If I understand you correctly, what you're proposing is the have a single function that sets a value for a property in all objects that have that property, and have all those objects expose it is as a public member? That pretty much limits your possibilities, doesn't it? Wouldn't that pretty much require you to maintain a bunch of functions for each property for each object with lists of objects that are affected by that property? That sounds like an absolute nightmare.

I was particularly thinking about having multiple graphs presenting those same statistics in various ways (graphs, charts, whatever) using MVC. I don't even think MVC is at all possible without setters, because without setters on the model there would be no way for them to know when their values have changed, or even to validate new incoming values. That also means views have no way of knowing when the model has been updated, thus effectively destroying the whole concept.



Well yes, in that case nobody in their right mind would stick to the 30FPS version. You're always going to have to balance maintainability against performance, though - my previous example was meant as an illustration of this. The more you make changes that improve performance, the more you're hurting maintainability and vice-versa. It's a fundamental trade-off, there's no way around it.

What can vary though, is the ratio by which they are related. In your 3D engine, for example, introducing even a little extra maintainability through getters and setters sets performance back unacceptably. In my example, the application will incur no performance hit to speak of. That's why I mentioned that you should use them whenever it makes sense. I think we can both agree that, if it's basically free, there is no sound reason not to use them, right?

Your point is valid as well and in fact further reinforces my point: game developers do tend to bias the balance towards performance, but they will never push it so far as to overly hurt maintainability. Because of the relative importance of performance they're willing to take a hit in modifiability, just as in my example you would be willing to take a performance hit for the increase in maintainability. It all depends on the relative importance of either in your application.

Voet, I'm not sure I fully understand your first example.

But as wv suggested, if one were to program an application that was THAT difficult to add a multiplier to a few variables, that's just bad programming. It wouldn't be difficult at all to structure classes in such a way that one could easily add a multiplier to variables before they were passed to some statistics, like a pie chart etc, and not the convoluted method you pondered, having functions for each property etc.

I agree it's obviously a balance between usability and performance. In fact that's one of the reasons that as of now, my 3D engine is only engineered for proprietary use. It wouldn't be quite as fast if I re-structured the whole thing to be easily usable to other developers (it would still be fast though :D )

And thus, if for a certain app getters and setters would be genuinely useful, and it wasn't an app where thousands of variables were being updated every frame, and therefore performance wasn't an issue - sure, use them if you want.

I know you said you're talking about software development in general, but obviously this is an AS3 forum, and I don't think it's a good idea to suggest that AS3 devs use getters/setters as a matter of course. You obviously didn't know that the AS3 compiler didn't streamline your code when you wrote that, but now you do, and as fast as AS3 is for a browser based software renderer, enough people have trouble getting good performance out of it as it is. We don't want to encourage people to make their applications run slower ;)

And Flash is mostly used for games/websites/motion graphics etc, rather than the more static applications you speak of. So most of the time, performance REALLY is important, and the better the performance you can squeeze out of AS3, the better product you'll be able to produce, generally speaking.

And in regards to rules/OOP principles etc, I guess one of the ways in which our opinions differ is that I feel rules are there to be broken. I feel that taking a rigid approach to programming is restraining. I feel you should do whatever it takes to get the desired result, or get max performance within reason (obviously no, I don't like code that's a horrible mess, I like my code neat and concise).

And to be honest, in regards to say cutting edge games or motion graphics, I don't think people would be pushing the boundaries of the various platforms around if they did stick to such a rigid approach. I feel you do have to break rules and do things in original ways to push the boundaries of what any given platform is capable of. Even if certain methods are somewhat hacky or "wrong".

Well that's my philosophy anyway ;)

dandylion13
January 18th, 2010, 10:35 AM
You guys are too smart for me!

I'm going back to my knitting :)

wvxvw
January 18th, 2010, 10:46 AM
I'm not talking about just AS3 here though, I'm talking about the entire field of software development regardless of language. As mentioned above, AS3 appears to be an exception to the general rule that getters and setters have little impact on performance, and you should adjust your decision whether to use them accordingly. That changes nothing to their usefulness though, and does not mean they shouldn't be used in general.

"In general" is a bit vague word :) In general in total programming - well, maybe, I don't really know because my knowledge is generally limited to scripting languages.
In general in AS3 - no, unless you absolutely need it (like in case with MXML or interface you cannot change), simply make it a function. Function makes it possible to pass a reference to what once was a class field and it does precisely what the setter / getter did before. Well, you will have more class fields in total, but this is only on the code editor level... in the compiled code it'll be the same, if not less.
I.e. imagine this:

public function get foo():Bar { ... };
// changes into
public function getFoo():bar { ... };
Think of how in C++ you can pass a reference (*) or in C# you can specify that a reference to a property is passed rather than value (ref) - I don't know if this is possible in Java though... So, surprisingly, if you design in an "oldish" style you gain back this ability, because once you used a function you can pass a setter of a simple type by reference!
It seems to me that setters and getters (as well as a bunch of other things in AS3) are half-baked and at present aren't really suitable for a good work... Once AS3 compiler will know how to inline them and the language will allow passing references (pointers, whatever you call it), then they will make sense, but for now it's like a car without steering wheel, well, it almost works, but it's not yet there :)

Voetsjoeba
January 18th, 2010, 12:48 PM
And thus, if for a certain app getters and setters would be genuinely useful, and it wasn't an app where thousands of variables were being updated every frame, and therefore performance wasn't an issue - sure, use them if you want.

That's the thing though, they're almost always useful



I know you said you're talking about software development in general, but obviously this is an AS3 forum, and I don't think it's a good idea to suggest that AS3 devs use getters/setters as a matter of course. You obviously didn't know that the AS3 compiler didn't streamline your code when you wrote that, but now you do, and as fast as AS3 is for a browser based software renderer, enough people have trouble getting good performance out of it as it is. We don't want to encourage people to make their applications run slower ;)

No, but we do want to encourage people to make their applications more maintainable if the circumstances allow it. I believe the SEI estimates that roughly 70% of a project's costs are spent during maintenance. Again, I realize this doesn't apply to AS3 so much, but it's all about good practice. If circumstances allow it but you can't be bothered to write AS3 code with proper principles in mind just because you don't think anyone will ever need to edit or revisit your code, then you're in for a treat if you ever start working on some larger projects. How do you think all those open source projects manage to get by?



And Flash is mostly used for games/websites/motion graphics etc, rather than the more static applications you speak of. So most of the time, performance REALLY is important, and the better the performance you can squeeze out of AS3, the better product you'll be able to produce, generally speaking.

I'll agree that with Flash you're likely to find more applications that are performance-constrained. Each one should figure out for itself where it stands on the balance between performance and maintainability, and act accordingly.



And in regards to rules/OOP principles etc, I guess one of the ways in which our opinions differ is that I feel rules are there to be broken. I feel that taking a rigid approach to programming is restraining. I feel you should do whatever it takes to get the desired result, or get max performance within reason (obviously no, I don't like code that's a horrible mess, I like my code neat and concise)

And to be honest, in regards to say cutting edge games or motion graphics, I don't think people would be pushing the boundaries of the various platforms around if they did stick to such a rigid approach. I feel you do have to break rules and do things in original ways to push the boundaries of what any given platform is capable of. Even if certain methods are somewhat hacky or "wrong".

Well that's my philosophy anyway ;)

Then I suppose we'll have to agree to disagree on that one :) I don't think you should break coding practices that have proven their worth for decades just because you can. If you have a sound reason to, then by all means go ahead and break 'em, but if not then at one point you're inevitably going to run into the same problems that people ran into 20 years ago and have actually long been solved by, you know, proper coding practices.

vangojames
July 23rd, 2010, 04:43 AM
Sorry for digging this up after so long but I just wanted to say that I totally agree with Voetsjoeba. Use Getters/Setters always unless the performance hit is completely unacceptable. One of the Golden rules of OOP is to program to an interface not a concrete class. If you don't use getters and setters, then you simply can't do this if your interface needs to have properties. If you maintain concrete classes throughout your application then you can't achieve decent encapsulation (unless you're working on a small project), and you'll find yourself having a maintenance nightmare!