(Since we’re MXNA’d now, I wanted to bring this post and maybe a couple of others back up to the top by reposting them. This was written back in October)
I was looking at this blog post by Tink about more strict Abstract constructors in Flash using Errors. I worked out a way that is a bit more formalized. It adds support for abstract methods and unlike Tink’s example, doesn’t require you to type out the string of the class name.
Download the source. Sorry, this link is dead, but the source is now part of AS3Lib
Actually, now it’s here: https://github.com/mimshwright/AbstractAS3
Basically, it works by throwing an error whenever you want a class to be subclassed or a method to be overridden. It’s a runtime error and doesn’t get thrown until you actually try to instantiate or run a method which. While this isn’t perfect it’s better than nothing.
It also checks the type in the constructor which allows you to add code to the constructor that will be inherited by the subclass upon instantiation without causing the errors (in other words, you can safely call super() without getting an error). It wraps up everything into an AbstractEnforcer utility class that simplifies the syntax.
The AbstractEnforcer.enforceConstructor() method uses a second utility function that you may find useful: strictIs(instance:Object, comparisonClass:Class) located in com.mimswright.utils. This function works just like the is operator but performs a strict comparison on the fully qualified class name. The result is that you will only get true back if instance‘s class is exactly the same as comparisonClass (with the is operator you would get true if instance was a subclass of comparisonClass). It’s a bit nicer than doing a string comparison of the class names.
I’m still looking for people to bang on it and see if it breaks or find more improvements so please check it out.
Note: This is AS3 only. You’ll need to have some way to compile AS3 to use this (like Flex Builder). You’ll also have to be a big geek and be into anime and Spawn action figures.
The code is set up to break as it is, but I left some commented code in there so you can try different scenarios.
Thanks to Tink and everyone.
Pingback: Using Abstract Classes in the Flash CS3/4 Library « dispatchEvent() Blogâ„¢
Pingback: IDisplayObject? – getting around the lack of an interface for the DisplayObject in Flash « dispatchEvent() Blogâ„¢