16 Oct 2006

Interfaces in AS2 and AS3 are only half-baked. You can place methods in an interface but that's only half the equation. The other half, for applications that use the event model, is events. As it stands AS2 and AS3 do not support a method of defining the events that an interface must implement. Going forward, this is essential to have in ActionScript if interfaces are to be useful in the event model. It is not enough to know which public methods an interface supports but which events you can listen for on instances that implement a given interface.

Add Your Comment

Spam Protection by WP-SpamFree

ActionScript 4 feature request: interfaces with events

  1. I usually handle this by adding a get method for the event type and / or event itself.

    function getProgressEventType(): String;
    function getProgressEvent(): ProgressEvent;

    Paul
  2. agreed!

    Tink
  3. Its a bit of a weird request you’re making. Interfaces are meant to be mandatory to implement by a class that implements that interface. Implementing events depends completly on the situation you are using certain classes in and can’t possible be mandatory to implement.

    Making the implementation of events mandatory also destroys the promotion of loose coupling and you might be better of using callbacks, or even worse let a child object have a reference to a parent object to call methods directly.

    pan69
  4. Not weird at all. What does an interface provide for you? It provides the safety in knowing that an instance will contain certain methods. That it will know what to do if you call a certain method. Similarly, if you can be certain that an interface will broadcast certain events, you can listen for those.

    Here’s a concrete example:

    You have an interface, IPreloadable that defines a contract for an object that is preloadable. You might, for example, dictate in the contract that the object must have a load() method that you call to start loading it. One characteristic that defines IPreloadable objects is that you can inspect them to get their current load progress. In the current status quo, the only way to this is to specify an additional method to get the load progress. Let’s call it getProgress(). (Or split this up to getBytesLoaded(), getBytesTotal(), etc.) Now think about what is required when using this: You need to constantly poll that object for its progress. Not good. Not the event model. Instead, what you should be doing is listening for an event. A progress event. But you have no way of specifying that in the interface.

    Now, if I could write:

    [as]
    interface IPreloadable
    {
    // IPreloadable objects must dispatch progress events
    event progress:ProgressEvent;

    public function load():Boolean
    }
    [/as]

    Then I could be sure that I could listen for progress events on any object that implements the IPreloadable interface.

    Adding events to interfaces in no way destroys loose coupling. Quite the opposite, it promotes interfaces to first class citizens in applications built on the event model and allows for a stronger *contract* (not coupling).

    aral
  5. You’re right Aral; it’s a nice idea. An interface is an abstract data type itself (and a class isn’t), so the event definition at interface level should be a feature.

    miguel
  6. good idea on that. but it also need to add a new type “event”, it that like .net’s delegate/event type?

    daniel yuen
  7. Hi Daniel: You’re right, it would need a new type for events. (I glossed over that in the example — taking it as a given.) I feel that this is natural for a system that is based on the event model.

    aral
  8. Would the compiler simply scan the implementing class for “at least one instance” of the event type declared in the interface?

    Are we talking class level or method level, or both?
    eg.
    - methodA must dispatch an eventA
    - classA must dispatch at least one eventA, eventB, eventC etc.

    This is certainly an interesting idea, and would provide for the robustness enjoyed by the traditional observer pattern when using the EventDispatcher mixin. I really love the flexibilty of ED but I’ve often questioned its use in complicated applications over using get/set methods because i have no automated checking of event usage, so this really would solve the issue.

    So how long till AS4 anyhows? ;-)

    ktec
  9. interface implementation should allow also property (get/set) definition, since they are a specialized form of method. if not, the whole point of property implementation in AS is lost in interfaces. if i could write:

    interface ISomethingable
    {
    function get SomeString():String;
    function set SomeString(val:String):Void;
    }

    it would simplify the interface a great deal to the consumer, since it could be casted to ISomethingable.SomeString for both operations.

    morpheus
  10. I was wondering, is there actually an official place for such feature requests?

    DEBEDb
  11. “I feel that this is natural for a system that is based on the event model”
    I don’t really agree with that: the Flex/AS3 Framework is based on events, not the langage. :o) Implement this kind of feature into the langage because the framework developers decided to use the EventDispatcher mixin wouldn’t be a good thing for me…
    Maybe a Metatag for that would help the IDE to propose the available event types.

    The only way to specify event for now is to use the Observer model, and I think it’s not a bad way at all:
    [as]package progress {
    public interface ProgressListener {
    function handleProgressEvent(e : ProgressEvent);
    }
    }

    package progress {
    public interface ProgressDispatcher {
    function addProgressListener(lst : ProgressListener);
    }
    }[/as]

    Some feature requests for my part:
    - being able to specify constants in interfaces
    - generics (typed arrays, dictionnaries, …)
    - parametric polymorphism (overloading).
    - be able to access variables to specify the [Bindable] metatag in FB2. If we want to save event type into static const, we’re still forced to use the plain string in those metatags…

    DEBEDb: It’s already possible to specify getters/setters in interfaces with AS3… ;o)

    LAlex
  12. Hi LAlex,

    I don’t really agree with that: the Flex/AS3 Framework is based on events, not the langage.

    I’m not disputing this. I’m saying that the language *should* be based on events. Or, in another way, that events should be made part of the language as they are central to development in Flash and Flex application. They are as important as objects and even more so than classes (which are, after all, still a stylistic element more than anything else in an *object*-oriented language).

    aral
  13. I agree that events are a really cool and a good way to have clean code, but the way AS (and ECMA) are oriented prevent to use them as a part of the langage, and it doesn’t seem to me that it’s a must-have: events are an implementation of a coding method, but that’s all…

    But it’s true that the C# event management is pretty cool, maybe ECMA should think of it? :-) But I think it’s also an implementation, using operator overwritting…

    ^_^

    LAlex
  14. [...] Aral Balkan has proposed that, just as AS3 allowed coders to put getter/setters into interfaces, AS4 should allow coders to put events like “ready” or “complete” inside the interface. I’ll sign up for that. Interfaces like ILoadable would be less cluttered, because they wouldn’t have to duplicate the functionality of EventDispatcher. [...]

    Building Pet 4: Interfaces
  15. AS4 or the next flash platform must render on the GPU. Silverlight is coming and the best way to win the battle is to blow them away before they get started. We must get some kind of interface to the GPU.

    Andrew Paul Simmons
  16. “AS4 or the next flash platform must render on the GPU”
    Doing that maybe will compromise the flash player hardware independence since it will require certain GPU hardware to work. Maybe it could check if GPU acceleration is provided and if not use the CPU… just a thought.

    There is a release date for AS4?
    I´m just getting my hands to AS3, I would be madness if this happens so soon and in my opinon it’s a bit unrespectful from Adobe to change the language so many times in a short period of time and a weakness of the product. It will be better for them to create a robust language and then provide new functionalties but not a new sintax/semantic.

    Polaco
  17. That feature will be available in AS5 only

    Quvet
  18. Maybe I’ve been slow to change but you guys are talking about AS4-AS5 like it’s some kind of a roll out phase. Dude heres an idea. how about the masterminds that come up with actionscript DO IT RIGHT THE FIRST TIME… YOU KNOW LIKE GOING TO THE MOON… YOU DO IT RIGHT THE FIRST TIME… I understand a programming language evolves over time but, this is starting to feel like a “High School Science Project” with Flash and Flex development. For starters the IDE in Flash and Flex doesn’t even compare to Visual Studio in logic and in grace, not to mention Error checking is a complete joke, and the intellisence works better in my email client than it does in Flash’s code view. So I have a great idea, how about we leave leave action script alone, and let the rest of the development community catch up. And focus on making the IDE better, more intuitive, take out the redundancy in the GUI vs Code.

    Darkrider
  19. Going to reply to my Extremely brash comments above. By saying I love Flash and I will defend it to the death The masterminds behind Flash/ActionScrip are doing a great job. But dude being someone who works in both Flash and Visual Studio, the reason Silver light is going to seriously hurt Flash and Flex isn’t because of the effectiveness of Action Script… it’s because of simple tools inside the Silver Light/Blend Visual Studio Development platforms like “Intellisense” and the Runtime Complier, not letting you compile jack chit’ unless the project works 100% without failure, or Seamless Database intergration you not only can create Database and populate it but you can make and a GridView to your project and animate it on screen. you can do all this in under 10 min…granted your using 3 programs to do it but the point is your using the same debugger you’d use in Silver Light that you’d use in Blend that you’d use in Visual Studio…

    So again instead of pushing actionscript even further, Let all work on making the Development Environment Better an more intuitive, more integrated with all other Adobe Development Platforms… I think then we’ll start to see big holes in Interactive Development and Adobe Products, and then when Adobe fills those holes, we won’t have anything to worry about when Silver light start to take hold.

    Darkrider
  20. Er… I just got off of a Silverlight project, using VisualStudio 2008 and I couldn’t disagree more. Granted, C# is a more robust language than AS3, but there were some major problems with application development. Perhaps you haven’t worked with with Flex before, but VS with Silverlight is dreadful in comparison. I found the error messages to be, at times, completely devoid of useful information. Intellisense is okay, however you run into some hurdles if you don’t already know the namespace of the class you want to use and already have it in the class since intellisense is completely ignorant of what is available. The dependency properties are obtuse and difficult to work with (intellisense is little help if any in this regard) and there isn’t a clear and robust way for you to communicate with the code behind from xaml. All this is made even worse by the horrific state of the documentation, which was useless half the time I tried to look something up. I certainly don’t think VisualStudio can boast any grace in comparison to FlexBuilder. Silverlight also seems to be more cumbersome at runtime, grinding through tasks which I have seen Flex perform efficiently. Silverlight seems to lean quite heavily on xaml, while punishing developers who try to do the same task in C#, resulting in thousands of lines of xaml code which, in addition to defining layout, which is the whole point of mark-up language, also defines functionality which can’t be efficiently ported to C#.

    Silverlight is nice for .NET developers who want to get a taste of the front end, but it has a very long way to go until it is a desirable environment to develop in for people accustomed to Flex. ActionScript does need to be more robust, and Adobe is working on it, as they should. And don’t forget, there were a lot of baby steps on the way to the moon, which is a far better analogy to the development of ActionScript than I think you realize.

    rob
  21. I would rather take FlashDevelop as a development environment than Visual Studio any day. Intellisense is not exclusive to Visual Studio.

    Joshua
  22. I fully agree with the post, but the way events are handled in AS3 seems to difficult things. We could just state that the interface extends EventDispatcher but that only gives us addEventListener and removeEventListener methods.

    It would be nice to have a C#-like event handling. We could just define that event in the interface:

    event onProgress;

    And we would use it this way:

    obj.onProgress += myEventHandler;

    Filipe
  23. it should support multithreading. It is a big mistake it doesn’t support multithreading, because it will be hard to implement a realtime application, specifically, large enterprise level app.

    Liang
  24. I agree with you that there should be some way to specify that a class should dispatch certain events. Maybe it might be better to use a different word than ‘interface’ though, just to avoid tying the concepts together for now.

    So it could be something like

    class SomeClass extends SomeBase implements ISomeInterface dispatches SomeNewFancyThing
    { … }

    Danny
  25. Casting as Sprite instances of interfaces that extend Sprite seems to work for adding listeners, e.g.:

    class MyClass extends Sprite implements IMyInterface

    // when using MyClass from client, cast instance as Sprite (which MyClass extends) to access built-in Sprite methods like addEventListener

    var myobj:IMyInterface;
    myobj = new MyClass();
    Sprite(MyClass).addEventListener(…

    jomoja
  26. The style of writing is quite familiar to me. Have you written guest posts for other bloggers?

    How to Get Six Pack Fast
  27. @Darkrider said: “the reason Silver light is going to seriously hurt Flash and Flex isn’t because of the effectiveness of Action Script… it’s because of simple tools inside the Silver Light/Blend Visual Studio Development platforms”

    Please let me introduce you to Amethyst :-)

    This is a Visual Studio Flex IDE from my company, SapphireSteel Software. It will have a full suite of Visual Studio tools for coding,, design, debugging etc. We will release two editions – a free ‘Personal Edition’ and a commercial ‘Professional’ edition. Amethyst is already available in beta and version 1.0 will be released in a few months.

    Both editions have IntelliSense, code formatting/colouring/folding, debugging with drill-down etc. Amethyst Professional will also have a drag-and-drop visual designer for Flex/AIR (Flex 3 md 4) plus enhanced debugging (tracepoints, conditional breakpoints etc.) – all seamlessly integrated into Visual Studio.

    More info on our web site. The blog is a good place to start: http://www.sapphiresteel.com/-Blog-

    best wishes
    Huw

    Huw Collingbourne
  28. But, if as you suggest AS interfaces were to support declaring events (on the class level) with:

    event progress:ProgressEvent;

    Wouldn’t you, in a similar fashion, also want to be able to declare styles, e.g.

    style doingGoodProgressEffect:SomeStyleType;

    But… a problem of AS abd Flex, imho, is the infiltration of so many keywords and concepts. It may be too late, but shouldn’t AS aim at simplification rather than continued keyword/concept creep?

    On the other hand, is there a particular reason why AS interfaces do not support declaration of (public) vars, instead of only supporting get/set properties?

    My gut feeling is that a more generic way to proceed would be to
    a) adjust how events/styles (or anything currently requiring decoration via “metadata” declaration) in Flex are declared, such that they are instead declared via vars/properties of a given type
    b) add support for var declaration to AS interfaces

    The alternative i.e. that of adding the possibility for AS interfaces to support class/method metada decorations, might well be feasible but I suspect my hide numerous issues that may dirty the approach…

    Mario Ruggier
  29. Hi,

    I’d suggest C# event handling …

    But for now, when I need an interface to define events, I do something like this:

    interface ISomeLoader {
    function addProgressListener(listener:Function,[whatever]):void;
    function removeProgressListener(listener:Function):void;
    }
    class SomeLoader implements ISomeLoader {
    public function addProgressListener(listener:Function,[whatever]):void{
    this.addEventListener(MyEvent.PROGRESS, listener);
    }
    public function removeProgressListener(listener:Function):void{
    this.removeEventListener(MyEvent.PROGRESS, listener);
    }
    }

    This doesn’t define the type of event, I specify it in the comments.

    Anyway this works fine for me and makes it easier to write the class clients.

    Filipe
  30. I think that’s what the metadata is meant to be for?

    Florian Salihovic
  31. Just thought I’d share some insight on the situation a bit. I’ve been developing interfaces in AS3 for years now, it’s where I like to start with a class. One thing you’ll notice is that interfaces cannot extend from classes. That is to say:

    public class MyClass { … }
    public interface MyInterface extends MyClass { … }

    Will not compile (which is to be expected). However, interfaces can extend other interfaces, in fact, interfaces can extend any number of interfaces.

    public interface MyBaseInterface { … }
    public interface MyInterface extends IEventDispatcher, MyBaseInterface { … }

    So the trick to get your interfaces to have the add/remove even listener methods is rather easy. The trick is to specify which events are part of the interface contract, which is not supported by the language at the moment. Perhaps someone can come up with an approach using Filipe’s method of specifying events at the class level combining interface inheritance.

    I myself enjoy the C# approach to events, in fact I wish Actionscript were C# to tell you the truth. I enjoy C# far more than I do AS3, however I enjoy the display list approach Adobe has taken in the Flash world.

    Darren S.
  32. Totally agree! One may want to be sure that an implementation dispatches certain events.

    Juan P. Reyes
  33. Just a follow up: I was inspired to come up with a solution to this problem so I’ve created a few classes and interfaces that will hopefully make specifying events on an interface a little easier.

    See my post here on my blog: http://gamesandtech.wordpress.com/2009/10/14/actionscript-3-specifying-events-on-interfaces/

    Darren S.
  34. Anyone read about as3 signals by robert penner?…………

    senthil kumaran
  35. Why not just define the events you need in a custom event class?

    Jack
  36. Plus, you can have your interface extend IEventDispatcher in order to allow you to add event listeners.

    Jack