Runtime Class creation in actionscript-why and for what purpose? - actionscript-3

Hi
Recently in actionscript it has been made possible to create Classes at runtime. Thi seems quite cool, but I am perplexed thinking of a situation in which this might be useful. Anyone have any ideas?

First of all, the uses for this in ActionScript is limited. So start of understanding what it actually is, and how other languages use it.
See Self-modifying code on wiki:
http://en.m.wikipedia.org/wiki/Self-modifying_code
Also see Reflection:
http://en.m.wikipedia.org/wiki/Reflection_(computer_science)
As an example of how it might be useful, I'm currently working with genetic algorithms to modify code at runtime. This way I can test every permutation (varying initial values and methods) without having to create classes for them, with the added bonus of exporting a .swf only containing the winning permutation.

Related

Always importing too many classes... I think

I have a basic problem with knowing which classes to import for a given application, renderer, AS package, mxml component, etc. There seems to be hundreds of classes (both mx and flash) and I'm never sure which one(s) to import... so I just keep adding import statements until the errors go away. Is there a reference somewhere that I don't know about? Or does this just come with experience? Also... does importing a load of classes actually make the file size larger or does Flex only import the classes used nregardless of what I specify? If it only uses what is needed, why wouldn't everyone just do: import mx.*;
I would suggest that if you find yourself bringing in tons of imports, you should ask yourself: Does this class do to much?
It is less of a technical issue, and more of problem of object-oriented design -- maintainability, testability and stability.
I do my best to limit my external dependencies. I try to conform to SOLID principles that tell me that classes should exist for one reason. If a class does too much, it is a "code smell" and an indication that you should split it up.
How much is too much? It is tough to have a specific litmus test or limit... I just ask myself "What does this class do"? If my answer contains an "and" in it, then I consider splitting it up.
I think your problem is a not a real problem if you use any half decent IDE. If you're not using one, you probably should (even if it's not stricly necessary and you can write and compile with notepad and the command line).
If you are using Flex/Flash Builder, it will add the imports automatically (and remove the unneeded ones as well). Also, you can use Ctrl + SPACE to prompt autocomplete, which should add the necessary imports.
Flash Develop also manages this for you (the shortcut was Ctrl + Shift + 1 if I recall correctly, but I haven't used FD for a while).
There are other IDEs out there that I haven't personally used but also have this very basic feature.
If you're using the Flash IDE, well, it really sucks for writting code, so you should probably consider writting your code in some other less brain-dead editor if you plan to do anything more than a couple of lines of code here and there (again, you can write code in the Flash IDE but why not taking advantage of better tools when they're available?).
When you get an error, look at the API Reference for the class, and then either import the whole package or just the class you want. Highlighting the class and hitting F1 should also work (but I never search help this way).
As for file size, see my answer on Is it possible to dynamically create an instance of user-defined Class in Action Script 3?
As Juan pointed out, use FlashDevelop, it is a great (and free) IDE.
If you're using FlashDevelop with the Flex Compiler, you can compile straight from FlashDevelop, and use the refactoring tools they offer to slim down your imports.
Aside from that though, if you're not referencing them, they don't get compiled, so it's not like your compiled swf is any bigger.

Why doesn't ActionScript have "generics"?

Can anyone tell me why ActionScript 3, a statically typed language, doesn't have generics? Is it too much work? A historical thing? Is there some way to "fake" it that I haven't picked up yet?
Edit: thanks a lot for the answers! The Vector class is basically what I was looking for, and the other information was helpful too.
The new Vector class is a form of generics that Actionscript 3 now supports when compiled for Flash Player 10. They don't support the specification of your own generic classes, yet.
I think Adobe will implement the ES4 standard eventually. It would be nice if they had a competitor who could push them quicker in the right direction. I was expecting a little more from the updates to AS3 when they moved to CS4, but I suppose the revolutionary Vector class will have to suffice.
It looks like they spent a lot of time beefing up the libraries for Flex and AIR, so maybe they'll go back to improving the language support later, but it probably isn't a real priority. Remember, Adobe is in it for the money, not for the feel good of making the sweetest possible language.
I believe it's a historical thing. ActionScript is based on ECMAScript (JavaScript is also based on ECMAScript). ECMAScript is a dynamically typed language, meaning that variables don't have their type declared. Generics are more useful in statically typed languages, wherein the type of variable is declared upfront. In a statically typed language, without generics you're stuck casting all the time from the root object (for example, Object in Java). This is not a problem in ECMAScript, because you can put anything you want into any data structure.
So why didn't ActionScript add generics when they added static typing to ECMAScript? I can't be sure of that, but I think the premise of your question is a bit off - there are generic-esque containers, such as Vector. I might think they'd keep the dynamically-typed containers of ECMAScript (objects and arrays) for backwards-compatibility, but they already broke that between AS2 and AS3, so I'm not sure.
Parameteric types ( the word 'generics' is usually used in ECMAScript for generic methods, rather than the combination of parametric types and runtime polymorphism used in Java ) were proposed as part of ES4, but ES4 fractured and much of the type system proposed for ES ( including the parts implemented in ActionScript ) are not going into the next version. I can't say whether or not Adobe would want to go that way by themselves.
Let's first get proper containers and algorithms in actionscript and then worry about generics...
as3 is not very different from javascript, btw, so your question would kind of apply to JS as well.

How to compile the generated AS

hope you can help me with this question.
So, I've been working for a while with Flex, and had the crazy idea to create pure AS project.
If I compile a Flex app with the -keep flag, the generated actionscript gets generated.
Do you guys know of a way to make it compile, without going trough the code and gluing it all together?
Thanks.
Generated ActionScript is really only provided for reference; it's not really intended to be repurposed in that sense. Indeed, if you even have any, you've most likely compiled your project already anyway (unless you got it from somewhere else), so one might ask why you'd want to compile the generated stuff rather than your own source -- but nonetheless, although I haven't actually tried it, you should be able to point the Flex compiler mxmlc at your generated source to compile it, provided you're able to get all your dependencies to line up (which may be what you mean by "gluing it all together").
Just a thought, although again, I haven't actually tried it, so your results may vary. What is it you're trying to do, though? Just curious. :)
Like Christian mentioned, the generated AS code is pretty much there to serve as a reference. Just for fun, I tried compiling it from the command line using mxmlc, but part of the problem with doing that is that the class files generated don't match the classes they represent. So, you'd need to start renaming a bunch of your class files so that compiling those could even work. Many of the other classes in Flex won't be compiled in either, for the same reason.
As an example, the project I tested this with, had only one mxml file of source code in it. The generated output was 45 files. I'm sure that if you really wanted to do this, and were willing to invest the time in cleaning things up you could. But I'm curious too - why would you want to do this?
Actually it was just mere curiosity. I wanted to understand how the framework works and see how it merges it all together to make the final application, as I thought that the generated actionscript files were just a step in between the final SWF file, so I tought there should be a way for it to grab those files and generate the final application.
Eventually I would have tried to create a pure actionscript project just for the heck of it to see how complicated it was and what errors could happen when developing other stuff.
I know it sounds crazy, but I had some spare time, ha ha ha.

LinqToSql Best Practices

I just started creating my data-access layer using LinqToSql. Everybody is talking about the cool syntax and I really like Linq in general.
But when I saw how your classes get generated if you drag some tables on the LinqContext I was amazed: So much code which nobody would need?!
So I looked how other people used LinqToSql, for example Rob Connery at his StoreFront Demo.
As I don't like the way that all this code is generated I created my domain layer by hand and used the generated classes as reference. With that solution I'm fine, as I can use the features provided by Linq (dereferred execution, lazy loading, ...) and my domain layer is quite easy to understand.
How are you using LinqToSql?
The created classes are not as heavy as it seems. Of course it takes quite a few lines of code, but all in all it is as lightweight as it can be for the features it's providing.
I used to create my own tables, too, but now instead I just use the LINQtoSQL DataContext. Why? Creating is simpler, the features are better, interoperability works, it is probably even faster than my own stuff (not in every aspect. Usually my own stuff was extremely fast in one thing, but the generic stuff was faster in everything else).
But the most important part: it is easier to bring new developers into the LINQ stuff than into my own. There are tutorials, example codes, documentation, everything, which I'd have to create for my code by myself. Same with using my stuff with other technology, like WCF or data binding. There are a lot of pitfalls to be taken care of.
I learned not to develop myself into a corner the hard way, it looks fast and easy at the start, is a lot more fun than learning how to use the libs, but is a real pain in the a after a few months down the road, usually even for myself.
After some time the novelty of creating my own data containers wears off, and I noticed the pain connected to adding a feature. A feature I would have had for free, if I had used the provided classes.
Next thing I had to explain my code to some other programmer. Had I used the provided classes, I could have pointed him to some web site to learn about the stuff. But for my classes, I had to train him himself, which took a long time and made it hard to get new people on a project.
LinqToSql generates a set of partial classes for your tables. You can add interface definitions to the 'other half' of these partial classes that implement your domain model.
Then, if you use the repository pattern to wrap access to the Linq queries, so that they return interface implementations of your objects (the underlying Linq objects), LinqToSql becomes quite flexible.
You can hand-write your own classes and either use the LINQ to SQL attributes to declare the mappings or an external XML file.
If you would like to stick with the existing designer and just modify the code generation process pick up my templates that let you tailor the generated code.
Use compiled queries. Linq to SQL is dog slow otherwise. Really.
We use our hand crafted domain model, along with the generated classes, plus a simple utility which utilizes reflection to convert between them when needed. We've contemplated writing a converter generator if we reach a point where reflection creates a performance bottleneck.

Does generated code need to be human readable?

I'm working on a tool that will generate the source code for an interface and a couple classes implementing that interface. My output isn't particularly complicated, so it's not going to be hard to make the output conform to our normal code formatting standards.
But this got me thinking: how human-readable does auto-generated code need to be? When should extra effort be expended to make sure the generated code is easily read and understood by a human?
In my case, the classes I'm generating are essentially just containers for some data related to another part of the build with methods to get the data. No one should ever need to look at the code for the classes themselves, they just need to call the various getters the classes provide. So, it's probably not too important if the code is "clean", well formatted and easily read by a human.
However, what happens if you're generating code that has more than a small amount of simple logic in it?
I think it's just as important for generated code to be readable and follow normal coding styles. At some point, someone is either going to need to debug the code or otherwise see what is happening "behind the scenes".
Yes!, absolutely!; I can even throw in a story for you to explain why it is important that a human can easily read the auto generated code...
I once got the opportunity to work on a new project. Now, one of the first things you need to do when you start writing code is to create some sort of connection and data representation to and from the database. But instead of just writing this code by hand, we had someone who had developed his own code generator to automatically build base classes from a database schema. It was really neat, the tedious job of writing all this code was now out of our hands... The only problem was, the generated code was far from readable for a normal human.
Of course we didn't about that, because hey, it just saved us a lot of work.
But after a while things started to go wrong, data was incorrectly read from the user input (or so we thought), corruptions occurred inside the database while we where only reading. Strange.. because reading doesn't change any data (again, so we thought)...
Like any good developer we started to question our own code, but after days of searching.. even rewriting code, we could not find anything... and then it dawned on us, the auto generated code was broken!
So now an even bigger task awaited us, checking auto generated code that no sane person could understand in a reasonable amount of time... I'm talking about non indented, really bad style code with unpronounceable variable and function names... It turned out that it would even be faster to rewrite the code ourselves, instead of trying to figure out how the code actually worked.
Eventually the developer who wrote the code generator remade it later on, so it now produces readable code, in case something went wrong like before.
Here is a link I just found about the topic at hand; I was acctually looking for a link to one of the chapters from the "pragmatic programmer" book to point out why we looked in our code first.
I think that depends on how the generated code will be used. If the code is not meant to be read by humans, i.e. it's regenerated whenever something changes, I don't think it has to be readable. However, if you are using code generation as an intermediate step in "normal" programming, the generated could should have the same readability as the rest of your source code.
In fact, making the generated code "unreadable" can be an advantage, because it will discourage people from "hacking" generated code, and rather implement their changes in the code-generator instead—which is very useful whenever you need to regenerate the code for whatever reason and not lose the changes your colleague did because he thought the generated code was "finished".
Yes it does.
Firstly, you might need to debug it -- you will be making it easy on yourself.
Secondly it should adhere to any coding conventions you use in your shop because someday the code might need to be changed by hand and thus become human code. This scenario typically ensues when your code generation tool does not cover one specific thing you need and it is not deemed worthwhile modifying the tool just for that purpose.
Look up active code generation vs. passive code generation. With respect to passive code generation, absolutely yes, always. With regards to active code generation, when the code achieves the goal of being transparent, which is acting exactly like a documented API, then no.
I would say that it is imperative that the code is human readable, unless your code-gen tool has an excellent debugger you (or unfortunate co-worker) will probably by the one waist deep in the code trying to track that oh so elusive bug in the system. My own excursion into 'code from UML' left a bitter tast in my mouth as I could not get to grips with the supposedly 'fancy' debugging process.
The whole point of generated code is to do something "complex" that is easier defined in some higher level language. Due to it being generated, the actual maintenance of this generated code should be within the subroutine that generates the code, not the generated code.
Therefor, human readability should have a lower priority; things like runtime speed or functionality are far more important. This is particularly the case when you look at tools like bison and flex, which use the generated code to pre-generate speedy lookup tables to do pattern matching, which would simply be insane to manually maintain.
You will kill yourself if you have to debug your own generated code. Don't start thinking you won't. Keep in mind that when you trust your code to generate code then you've already introduced two errors into the system - You've inserted yourself twice.
There is absolutely NO reason NOT to make it human parseable, so why in the world would you want to do so?
-Adam
One more aspect of the problem which was not mentioned is that the generated code should also be "version control-friendly" (as far as it is feasible).
I found it useful many times to double-check diffs in generated code vs the source code.
That way you could even occasionally find bugs in tools which generate code.
It's quite possible that somebody in the future will want to go through and see what your code does. So making it somewhat understandable is a good thing.
You also might want to include at the top of each generated file a comment saying how and why this file was generated and what it's purpose is.
Generally, if you're generating code that needs to be human-modified later, it needs to be as human-readable as possible. However, even if it's code that will be generated and never touched again, it still needs to be readable enough that you (as the developer writing the code generator) can debug the generator - if your generator spits out bad code, it may be hard to track down if it's difficult to understand.
I would think it's worth it to take the extra time to make it human readable just to make it easier to debug.
Generated code should be readable, (format etc can usually be handled by a half decent IDE). At some stage in the codes lifetime it is going to be viewed by someone and they will want to make sense of it.
I think for data containers or objects with very straightforward workings, human readability is not very important.
However, as soon as a developer may have to read the code to understand how something happens, it needs to be readable. What if the logic has a bug? How will anybody ever discover it if no one is able to read and understand the code? I would go so far as generating comments for the more complicated logic sections, to express the intent, so it's easier to determine if there really is a bug.
Logic should always be readable. If someone else is going to read the code, try to put yourself in their place and see if you would fully understand the code in high (and low?) level without reading that particular piece of code.
I wouldn't spend too much time with code that never would be read, but if it's not too much time i would go through the generated code. If not, at least make comment to cover the loss of readability.
If this code is likely to be debugged, then you should seriously consider to generate it in a human readable format.
There are different types of generated code, but the most simple types would be:
Generated code that is not meant to be seen by the developer. e.g., xml-ish code that defines layouts (think .frm files, or the horrible files generated by SSIS)
Generated code that is meant to be a basis for a class that will be later customized by your developer, e.g., code is generated to reduce typing tedium
If you're making the latter, you definitely want your code to be human readable.
Classes and interfaces, no matter how "off limits" to developers you think they should be, would almost certainly fall under generated code type number 2. They will be hit by the debugger at one point of another -- applying code formatting is the least you can do the ease that debugging process when the compiler hits those generated classes
Like virtually everybody else here, I say make it readable. It costs nothing extra in your generation process and you (or your successor) will appreciate it when they go digging.
For a real world example - look at anything Visual Studio generates. Well formatted, with comments and everything.
Generated code is code, and there's no reason any code shouldn't be readable and nicely formatted. This is cheap especially in generated code: you don't need to apply formatting yourself, the generator does it for you everytime! :)
As a secondary option in case you're really that lazy, how about piping the code through a beautifier utility of your choice before writing it to disk to ensure at least some level of consistency. Nevertheless, almost all good programmers I know format their code rather pedantically and there's a good reason for it: there's no write-only code.
Absolutely yes for tons of good reasons already said above. And one more is that if your code need to be checked by an assesor (for safety and dependability issues), it is pretty better if the code is human redeable. If not, the assessor will refuse to assess it and your project will be refected by authorities. The only solution is then to assess... the code generator (that's usually much more difficult ;))
It depends on whether the code will only be read by a compiler or also by a human. In addition, it matters whether the code is supposed to be super-fast or whether readability is important. When in doubt, put in the extra effort to generate readable code.
I think the answer is: it depends.
*It depends upon whether you need to configure and store the generated code as an artefact. For example, people very rarely keep or configure the object code output from a c-compiler, because they know they can reproduce it from the source every time. I think there may be a similar analogy here.
*It depends upon whether you need to certify the code to some standard, e.g. Misra-C or DO178.
*It depends upon whether the source will be generated via your tool every time the code is compiled, or if it will you be stored for inclusion in a build at a later time.
Personally, if all you want to do is build the code, compile it into an executable and then throw the intermediate code away, then I can't see any point in making it too pretty.