Aspect Oriented Programming Library/Framework for Actionscript 3? - actionscript-3

I'm looking for a full featured AOP Library for Actionscript 3.
The following projects I noticed so far, but they all seem to have their problems:
http://farmcode.org/page/Sodality.aspx
looks most promising so far, however it requires you to create a whole new class for every AOP "call" I believe, and it forces you to follow quite a lot of restrictions, anyone has experience with it?
http://code.google.com/p/loom-as3/
this one is discontinued
http://code.google.com/p/floxy/
dynamic proxy generation? this isn't really AOP as I know it, right?
http://code.google.com/p/flemit/
dynamic byte code generation? this is something AOP needs I think, but not the full featured AOP framework I am looking for
Does anyone know of a better solution? Or does anyone have any experiences with AOP in Actionscript 3?
Best regards,
Tom

AOP in ActionScript 3 is really hard. All aproaches have their problems:
proxying: actually works fine and transparent to the programmer, but not to the runtime. If any function signature expects an object of type A, then a proxy to an object of type A will fail to pass the typecheck
bytecode generation: well, sort of works, but not too good. loading bytecode in AVM2 is asynchronous, so you can't do it just in time. Also, once bytecode is loaded, there's no way of discarding it, so you can not modify a class a second time.
anything else is verbose
What you can do is to use Haxe. Not only does Haxe have other advantages over AS3, but it also allows some AOP. There are two approaches:
Dynamic Methods
In Haxe, you can declare methods to be dynamic. These can be replaced at runtime to provide advices. Let me explain, what happens under the hood. The following Haxe code:
public function foo(param1:Type1):Type2 { /*body*/ }
public dynamic function bar(param1:Type1):Type2 { /*body*/ }
Is the equivalent of the following AS3 code:
public function foo(param1:Type1):Type2 { /*body*/ }
public var bar:Function = function (param1:Type1):Type2 { /*body*/ }
Using the latter always performs worse than the former, since there's a lot of runtime type checking involved. In Haxe however, you do not lose the compile time benefits of strict typing, unlike in AS3.
Likewise, using Haxe's accessors (that are indeed very different from AS3's), you can also use AOP for properties:
public var foo(get_foo, set_foo):Type;
dynamic function get_foo() {//Haxe will automatically infer types: http://haxe.org/ref/type_infer
return this.foo;
}
dynamic function set_foo(param) {
return this.foo = param;
}
Any methods, that are dynamic can be replaced at runtime to do whatever you wish. AS2 allowed this, and libraries like as2lib provided AOP. unfortunately, it is no longer available. But I guess you can figure out the rest on you own.
Proxying
Haxe has the notion of anonymous types. At runtime, these are merely * (thus a perfomance loss is to be expected), but at compile time, they are type safe. What you can do, is create a proxy to an object of whatever type you need and use it as AOP container. In your whole code, you never use its type explicetely, but rather an equivalent anonymous type. The problem with proxying I described will be gone. The only thing you need to do is to make an unsafe cast of your proxy to that anonymous type.

Check out Mixing Loom, a foundation for AOP in Flex / ActionScript:
http://www.jamesward.com/2011/04/26/introducing-mixing-loom-runtime-actionscript-bytecode-modification

Related

Pros of specifying type of event in function?, ActionScript 3

When creating a MouseEvent-triggered function, you can write
public function Hover(e) {
...
}
instead of
public function Hover(e:MouseEvent):void {
...
}
What are the advantages of using the latter, more specific way of defining a function? Will this affect the garbage collector, or other less obvious things?
Specifying a type gives you type safety at compile time.
That leads to benefits like compile time errors (instead of runtime errors) and code completion in your development environment.
It also adds to the readability, because the type is clearly stated.

Is it possible to write an AS3 library with Haxe that uses type parameters?

First a little background: I'm looking for a way to create a "collection" library that abstracts the Flash Player version based implementation (Vector on FP10, Array on FP9) away from the calling code. I've already written a small AS3 lib doing that but...
...the performance is bad (especially because of two levels of indirection and the runtime type checks on the Array implementation)
...the code is ugly (since Vector types need to be defined at compiletime I needed a factory returning concrete Vector instances based on an Enum that contains only the supported types)
I'm currently looking into Haxe as a possible solution since it supports type parameters and is able to compile to various Flash Player versions (and apparently compiles into mmore optimized bytecode).
Now, my question is: Is there a way to write a library in Haxe that can be used like this in AS3 code
var foo:IMyInterface = new MyImplementation(int);
var bar:IMyInterface = new MyImplementation(getDefinitionByName("my.package.MyClass"));
with IMyInterface exposing the required methods (push, pop, ...)?
The basic idea is that I want to provide the type information at runtime and get a typesafe Flash Player version independent "collection" for use in the calling code without having to bother with conditional compilation fragments all over the place.
Can Haxe do something like that and if yes, how can I make it work?
There's an opportunity in Haxe to override native classes (e.g. int) in Haxe. take a look at the Metadata manual. Metadata has been added in version 2.06.
As for analogue of getDefinitionByName() method. Take a look at resolveClass() method of the Type class.

Class design frustrations moving from Java to ActionScript

I primarily work in Java, but I've recently started using ActionScript 3.0 for a multi-player Flash game that I am helping to develop. The project is in it's early stages, so I'm still working on the class structure. I keep running into limitations with the ActionScript language when I try to use many of the OOP features I expect in Java.
For example:
I need an abstract Character class. There is no reason why Character would ever be instantiated, but ActionScript doesn't support abstract classes. As a result my code has this comment at the top:
Character should be an abstract class,
but AS doesn't support abstract
classes.
DO NOT CREATE AN INSTANCE
OF THIS CLASS. (Only instantiate
classes that extend this one (ex.
Player, Zombie))
As a result of the design of Flixel (the library we are using), I need to have a CharacterGroup class with an inner class Character so that a CharacterGroup can also contain other sprites like guns and stuff. In Java, I would use an inner class. ActionScript doesn't support inner classes. There is something called a "helper class", but helper classes are not inherited, which makes them useless in this context.
My question is this: Is ActionScript's ability to deal with OOP design just less developed or am finding ActionScript so frustrating because I am trying to write it as if it were Java instead of working my head around how ActionScript was desinged?
In other words, is the "correct" way of doing OO design different in ActionScript than it is in Java?
(Note: I'm not asking for opinions about why ActionScript is better/worse than Java. I'm only asking if I am coding correctly or trying to pull too much of my experience from Java.)
Thanks!
AS3 is not missing features and you cannot define it as 'less developed'.
Firstly for your problem - there are ways around the abstract class methodology.
For your abstract class Character - you can make it so the user developer receives an error on trying to instantiate it.
package com.strangemother.database.abstract
{
public class CentralDispatch extends EventDispatcher
{
private static var _centralDispatch:CentralDispatch;
public static function getInstance():CentralDispatch
{
if(!_centralDispatch)
_centralDispatch = new CentralDispatch(SingletonLock);
return _centralDispatch;
}
public function CentralDispatch(lock:Class)
{
if(!lock is SingletonLock)
{
throw new Error("CentralDispatch is a singleton. Use CentralDispatch.getInstance() to use.");
}
}
}
}
internal class SingletonLock{}
AS you can see - this must be used by the '.getInstance Method' - but to extend of that, only this class can make a new instace of itself as its the only class of which can see the internal class 'SingletonLock{}'.
For your purpose - you may remove the 'getInstance()' method and force another way the user to receive an instance of this class.
This should also display the ability to make internal classes. These cannot be seen by any other class - only this package and the parent class CentralDispatch can use it.
Another way you may use the abstract function method - is write then into an interface
package com.strangemother.database.engines
{
import com.strangemother.database.Model;
import com.strangemother.database.ModelSchema;
import com.strangemother.database.events.ModelEvent;
public interface IEngine
{
/**
* Reads modelSchema and calls generateModel upon
* each model found.
* */
function generateModelSchema(modelSchema:ModelSchema=null):String
/**
* Generate your CREATE syntax model to output to your SQL
*
* If you are extending the framework with your own database
* engine, you must override this with your own model generation
* format.
* */
function generateModel(model:Model):String
}
}
then at any point to use this, you implement it at class level
public class SQLite3 extends EngineBase implements IEngine
{
now my SQLite3 class must have the methods defined in IEngine
I much prefer to write classes with defined functions of which are overridden when implemented.
AbstractBase.as
/**
* connect to the database. This is not usually
* required as the abstraction layer should
* automatically connect when required.
* */
public function connect(onComplete:Function=null):void
{
SQLite3 of which extends AbstractionBase at some point
overide public function connect(onComplete:Function=null):void
Now to refute #Allan's comment of it being less developed (Sorry dude)
No operator overloading - thats correct but neither does Java. it wasn't applied to ensure AS3 was readable.
function overloading - You can't hard type it, but you can have function makeTea(...args) passing in as many or as little data as you wish. you've also got getters/setters.
for inline functions you can create anonymous functions.
var myFunction:Function = Function(name:String):String{ return name + ' - rocks!'; }
You've got dynamic classes therefore class level overloading -
and good example of real code is Flex Lib - it open source and you can read read how all these elements are managed by glacing through the code.
It is somewhat subjective, but personally, I would say that the "correct" way of doing OO design in AS3 is the same as Java and yes AS3 is just less developed.
AS2 was very much prototype based much like JavaScript currently is, althought as with JavaScript you could still program it to fit a classical style. Then along came AS3 which was based off a draft of the ECMAScript edition 4. The update to the ECMAScript made it more classical, akin to Java (JavaScript 2 which was going to be based on it, but was dropped as members of the commitee deemed it changed too much). So while AS3 is now a more classical Java style language, as you have found out, it is light on language features. Off the top of my head it is missing things like:
operator overloading
function overloading
generics
abstract classes
inline functions
inner classes that you pointed out
and probably a lot more things that other languages have that I am not aware of. It is understandable that it is annoying to not be able to use language features that you are used to but most of the time I have come to learn that the things lacking are luxuries*. You can get by without them its just at times can make your code a little more dangerous and verbose and thats just something you have to learn to live with.
There are a few hack ways to try and emulate some of these features but I rarely bother.
*You can also try looking at the language Haxe. The code is compiled to LLVM to ABC bytecode. The Haxe language supports generics, inline functions, conditional compilation (and more). I use it whenever I am writing a library.

What's the difference between closures and traditional classes?

What are the pros and cons of closures against classes, and vice versa?
Edit:
As user Faisal put it, both closures and classes can be used to "describe an entity that maintains and manipulates state", so closures provide a way to program in an object oriented way using functional languages. Like most programmers, I'm more familiar with classes.
The intention of this question is not to open another flame war about which programming paradigm is better, or if closures and classes are fully equivalent, or poor man's one-another.
What I'd like to know is if anyone found a scenario in which one approach really beats the other, and why.
Functionally, closures and objects are equivalent. A closure can emulate an object and vice versa. So which one you use is a matter of syntactic convenience, or which one your programming language can best handle.
In C++ closures are not syntactically available, so you are forced to go with "functors", which are objects that override operator() and may be called in a way that looks like a function call.
In Java you don't even have functors, so you get things like the Visitor pattern, which would just be a higher order function in a language that supports closures.
In standard Scheme you don't have objects, so sometimes you end up implementing them by writing a closure with a dispatch function, executing different sub-closures depending on the incoming parameters.
In a language like Python, the syntax of which has both functors and closures, it's basically a matter of taste and which you feel is the better way to express what you are doing.
Personally, I would say that in any language that has syntax for both, closures are a much more clear and clean way to express objects with a single method. And vice versa, if your closure starts handling dispatch to sub-closures based on the incoming parameters, you should probably be using an object instead.
Personally, I think it's a matter of using the right tool for the job...more specifically, of properly communicating your intent.
If you want to explicitly show that all your objects share a common definition and want strong type-checking of such, you probably want to use a class. The disadvantage of not being able to alter the structure of your class at runtime is actually a strength in this case, since you know exactly what you're dealing with.
If instead you want to create a heterogeneous collection of "objects" (i.e. state represented as variables closed under some function w/inner functions to manipulate that data), you might be better off creating a closure. In this case, there's no real guarantee about the structure of the object you end up with, but you get all the flexibility of defining it exactly as you like at runtime.
Thank you for asking, actually; I'd responded with a sort of knee-jerk "classes and closures are totally different!" attitude at first, but with some research I realize the problem isn't nearly as cut-and-dry as I'd thought.
Closures are very lightly related to classes. Classes let you define fields and methods, and closures hold information about local variables from a function call. There is no possible comparison of the two in a language-agnostic manner: they don't serve the same purpose at all. Besides, closures are much more related to functional programming than to object-oriented programming.
For instance, look at the following C# code:
static void Main(String[] args)
{
int i = 4;
var myDelegate = delegate()
{
i = 5;
}
Console.WriteLine(i);
myDelegate();
Console.WriteLine(i);
}
This gives "4" then "5". myDelegate, being a delegate, is a closure and knows about all the variables currently used by the function. Therefore, when I call it, it is allowed to change the value of i inside the "parent" function. This would not be permitted for a normal function.
Classes, if you know what they are, are completely different.
A possible reason of your confusion is that when a language has no language support for closures, it's possible to simulate them using classes that will hold every variable we need to keep around. For instance, we could rewrite the above code like this:
class MainClosure()
{
public int i;
void Apply()
{
i = 5;
}
}
static void Main(String[] args)
{
MainClosure closure;
closure.i = 4;
Console.WriteLine(closure.i);
closure.Apply();
Console.WriteLine(closure.i);
}
We've transformed the delegate to a class that we've called MainClosure. Instead of creating the variable i inside the Main function, we've created a MainClosure object, that has an i field. This is the one we'll use. Also, we've built the code the function executes inside an instance method, instead of inside the method.
As you can see, even though this was an easy example (only one variable), it is considerably more work. In a context where you want closures, using objects is a poor solution. However, classes are not only useful for creating closures, and their usual purpose is usually far different.

How should I refactor my code to remove unnecessary singletons?

I was confused when I first started to see anti-singleton commentary. I have used the singleton pattern in some recent projects, and it was working out beautifully. So much so, in fact, that I have used it many, many times.
Now, after running into some problems, reading this SO question, and especially this blog post, I understand the evil that I have brought into the world.
So: How do I go about removing singletons from existing code?
For example:
In a retail store management program, I used the MVC pattern. My Model objects describe the store, the user interface is the View, and I have a set of Controllers that act as liason between the two. Great. Except that I made the Store into a singleton (since the application only ever manages one store at a time), and I also made most of my Controller classes into singletons (one mainWindow, one menuBar, one productEditor...). Now, most of my Controller classes get access the other singletons like this:
Store managedStore = Store::getInstance();
managedStore.doSomething();
managedStore.doSomethingElse();
//etc.
Should I instead:
Create one instance of each object and pass references to every object that needs access to them?
Use globals?
Something else?
Globals would still be bad, but at least they wouldn't be pretending.
I see #1 quickly leading to horribly inflated constructor calls:
someVar = SomeControllerClass(managedStore, menuBar, editor, sasquatch, ...)
Has anyone else been through this yet? What is the OO way to give many individual classes acces to a common variable without it being a global or a singleton?
Dependency Injection is your friend.
Take a look at these posts on the excellent Google Testing Blog:
Singletons are pathologic liars (but you probably already understand this if you are asking this question)
A talk on Dependency Injection
Guide to Writing Testable Code
Hopefully someone has made a DI framework/container for the C++ world? Looks like Google has released a C++ Testing Framework and a C++ Mocking Framework, which might help you out.
It's not the Singleton-ness that is the problem. It's fine to have an object that there will only ever be one instance of. The problem is the global access. Your classes that use Store should receive a Store instance in the constructor (or have a Store property / data member that can be set) and they can all receive the same instance. Store can even keep logic within it to ensure that only one instance is ever created.
My way to avoid singletons derives from the idea that "application global" doesn't mean "VM global" (i.e. static). Therefore I introduce a ApplicationContext class which holds much former static singleton information that should be application global, like the configuration store. This context is passed into all structures. If you use any IOC container or service manager, you can use this to get access to the context.
There's nothing wrong with using a global or a singleton in your program. Don't let anyone get dogmatic on you about that kind of crap. Rules and patterns are nice rules of thumb. But in the end it's your project and you should make your own judgments about how to handle situations involving global data.
Unrestrained use of globals is bad news. But as long as you are diligent, they aren't going to kill your project. Some objects in a system deserve to be singleton. The standard input and outputs. Your log system. In a game, your graphics, sound, and input subsystems, as well as the database of game entities. In a GUI, your window and major panel components. Your configuration data, your plugin manager, your web server data. All these things are more or less inherently global to your application. I think your Store class would pass for it as well.
It's clear what the cost of using globals is. Any part of your application could be modifying it. Tracking down bugs is hard when every line of code is a suspect in the investigation.
But what about the cost of NOT using globals? Like everything else in programming, it's a trade off. If you avoid using globals, you end up having to pass those stateful objects as function parameters. Alternatively, you can pass them to a constructor and save them as a member variable. When you have multiple such objects, the situation worsens. You are now threading your state. In some cases, this isn't a problem. If you know only two or three functions need to handle that stateful Store object, it's the better solution.
But in practice, that's not always the case. If every part of your app touches your Store, you will be threading it to a dozen functions. On top of that, some of those functions may have complicated business logic. When you break that business logic up with helper functions, you have to -- thread your state some more! Say for instance you realize that a deeply nested function needs some configuration data from the Store object. Suddenly, you have to edit 3 or 4 function declarations to include that store parameter. Then you have to go back and add the store as an actual parameter to everywhere one of those functions is called. It may be that the only use a function has for a Store is to pass it to some subfunction that needs it.
Patterns are just rules of thumb. Do you always use your turn signals before making a lane change in your car? If you're the average person, you'll usually follow the rule, but if you are driving at 4am on an empty high way, who gives a crap, right? Sometimes it'll bite you in the butt, but that's a managed risk.
Regarding your inflated constructor call problem, you could introduce parameter classes or factory methods to leverage this problem for you.
A parameter class moves some of the parameter data to it's own class, e.g. like this:
var parameterClass1 = new MenuParameter(menuBar, editor);
var parameterClass2 = new StuffParameters(sasquatch, ...);
var ctrl = new MyControllerClass(managedStore, parameterClass1, parameterClass2);
It sort of just moves the problem elsewhere though. You might want to housekeep your constructor instead. Only keep parameters that are important when constructing/initiating the class in question and do the rest with getter/setter methods (or properties if you're doing .NET).
A factory method is a method that creates all instances you need of a class and have the benefit of encapsulating creation of the said objects. They are also quite easy to refactor towards from Singleton, because they're similar to getInstance methods that you see in Singleton patterns. Say we have the following non-threadsafe simple singleton example:
// The Rather Unfortunate Singleton Class
public class SingletonStore {
private static SingletonStore _singleton
= new MyUnfortunateSingleton();
private SingletonStore() {
// Do some privatised constructing in here...
}
public static SingletonStore getInstance() {
return _singleton;
}
// Some methods and stuff to be down here
}
// Usage:
// var singleInstanceOfStore = SingletonStore.getInstance();
It is easy to refactor this towards a factory method. The solution is to remove the static reference:
public class StoreWithFactory {
public StoreWithFactory() {
// If the constructor is private or public doesn't matter
// unless you do TDD, in which you need to have a public
// constructor to create the object so you can test it.
}
// The method returning an instance of Singleton is now a
// factory method.
public static StoreWithFactory getInstance() {
return new StoreWithFactory();
}
}
// Usage:
// var myStore = StoreWithFactory.getInstance();
Usage is still the same, but you're not bogged down with having a single instance. Naturally you would move this factory method to it's own class as the Store class shouldn't concern itself with creation of itself (and coincidentally follow the Single Responsibility Principle as an effect of moving the factory method out).
From here you have many choices, but I'll leave that as an exercise for yourself. It is easy to over-engineer (or overheat) on patterns here. My tip is to only apply a pattern when there is a need for it.
Okay, first of all, the "singletons are always evil" notion is wrong. You use a Singleton whenever you have a resource which won't or can't ever be duplicated. No problem.
That said, in your example, there's an obvious degree of freedom in the application: someone could come along and say "but I want two stores."
There are several solutions. The one that occurs first of all is to build a factory class; when you ask for a Store, it gives you one named with some universal name (eg, a URI.) Inside that store, you need to be sure that multiple copies don't step on one another, via critical regions or some method of ensuring atomicity of transactions.
Miško Hevery has a nice article series on testability, among other things the singleton, where he isn't only talking about the problems, but also how you might solve it (see 'Fixing the flaw').
I like to encourage the use of singletons where necessary while discouraging the use of the Singleton pattern. Note the difference in the case of the word. The singleton (lower case) is used wherever you only need one instance of something. It is created at the start of your program and is passed to the constructor of the classes that need it.
class Log
{
void logmessage(...)
{ // do some stuff
}
};
int main()
{
Log log;
// do some more stuff
}
class Database
{
Log &_log;
Database(Log &log) : _log(log) {}
void Open(...)
{
_log.logmessage(whatever);
}
};
Using a singleton gives all of the capabilities of the Singleton anti-pattern but it makes your code more easily extensible, and it makes it testable (in the sense of the word defined in the Google testing blog). For example, we may decide that we need the ability to log to a web-service at some times as well, using the singleton we can easily do that without significant changes to the code.
By comparison, the Singleton pattern is another name for a global variable. It is never used in production code.