A different use for custom namespaces (2/2)
by Ruben
Note that to keep the focus on the abstract/theoretical part of the subject I seperated the content over two seperate posts (of which this is the second). The previous explains the idea while this one shows a possbible use-case. I suggest you read the first post if you haven't already, it'll make things a lot more clear.
This post provides some example-code for the concept presented in my previous post, please note that this post serves only to add some concrete material to the abstract idea presented in the previous post and that the focus should be on the latter rather than the former. This post is not at all about best practices or good/bad code-architecture.
I first started thinking about using namespaces for overriding methods when at the end of july I was talking to Tommy about a problem he was having. He had overridden addChild() in some distant DisplayObject subclass but in some situations still needed to use the original implementation of the method. Because for this he used super.addChild() he was forced to put a lot of different logic in that one single subclass.
The implementation of the double-overriding popped up when I suggested to store the original addChild() functionality in a duplicate function defined with a custom namespace and the same name, and then put the rest of the functionality in a subclass of the class that would override addChild():
// DisplayObjectOverridden.as: package { import flash.display.DisplayObject; import flash.display.Sprite; public class DisplayObjectOverridden extends Sprite { public function DisplayObjectOverridden () { super(); } override public function addChild(child:DisplayObject):DisplayObject { // custom functionality } original function addChild (child:DisplayObject):DisplayObject { return super.addChild(child); } } }
// OtherFunctionality.as: package { import flash.display.Sprite; public class OtherFunctionality extends DisplayObjectOverridden { public function OtherFunctionality () { var normalChild:Sprite = new Sprite(); addChild(normalChild); var specialChild:Sprite = new Sprite(); original::addChild(specialChild); } } }
// original.as: package { public namespace original; }
Comments
Faltou implementar o removeChild, mas, bem útil a idéia.
Hi Ruben,
Can this also be done with a constructor? or only with non-constructor methods?
Cheers, Sid
Hey Sid,
I’m pretty sure the compiler will start complaining if you use any namespace other than the native
publicon your constructors, you’re welcome to try it out though..- Ruben