-
Notifications
You must be signed in to change notification settings - Fork 0
Traits
Traits is a language extension that adds a multiple inheritance ability to ActionScript3.
Unlike any other similar hack, this solution just provides a behavior that is very like multiple inheritance, hiding all redundant substances from user, meanwhile the generated code still stands on “best OOP practices”. The only thing you need is to add a trait in a list of implemented classes. The editor does the rest. Furthermore, it also provides some Type system checks to avoid errors in extending classes by means of composition. By the way, a similar approach is used in Groovy++ language.
##Advantages of Using
- Tight integration with IDE, its navigation tools and bookmarks.
- Well-organized view of code. Every implementation has a name: an interface name + “Impl”.
- Boost of the usability. In a class that uses this behavior, it needs only to add such an interface to the implemented list.
- Code of Creature class is not “littered” with excessive entities.
##Implementation
trait traitName extends ClassConcept
To get started with traits language extension, first create a main class
public class Elephant extends Sprite implements <none> {
public function Elephant() {
}
}
Second, create an interface
with a single method.
public interface Talk extends <none> {
function talk() : void;
}
Just after the import of traits language extension, a new tab named “Traits” will appear at the bottom of the screen. Trait implementation can be created with a right-click on this tab. Note how this is now the trait Talk rather than the interface Talk:
trait Talk extends <none> {
public function talk() : void {
trace "Weeeep!"; // let's talk
}
}
Now we return to our main class and add the newly created trait to its declaration. The editor added an “i” to the right of the interface name. It means that the interface has a default implementation — it has trait behavior.
// Main class will look like this
public class Elephant extends Sprite implements Talk(i){
public function Elephant() {
talk(); // now our Elephant will be able to talk
}
}
##The Generated Code
The Trait language extension’s essence is to hide redundant entities and organize relationships between code artifacts. In fact, we solve two task at once: we get multiple inheritance and remain operating a “pure” OOP code. To prove this, let’s refer to the generated code:
public class Elephant extends Sprite implements Talk {
private var delegate_a : Talk = new TalkImpl(this) ;
public function Elephant( ){
talk();
}
public function talk ( ) : void {
delegate_a.talk();
}
}
}
public interface Talk {
function talk ( ) : void ;
}
}
public class TalkImpl implements Talk {
public function TalkImpl( agregator : Object ){
}
public function talk ( ) : void {
trace "Weeeeep!" //let's talk
}
}