First Look at Dart Mixins

You can use mixins to help inject behavior into your classes without using inheritance. Use a mixin when you have shared functionality that doesn't fit well in a is-a relationship.



Dart supports a basic form of mixins as of the M3 release in early 2013. The language designers expect to expand on mixins' abilities in future versions of the language.

Surprisingly, you've been using the concept of a mixin all along. Dart considers a mixin as the delta between a subclass and its superclass. That is, every time you define an is-a relationship with the extends keyword, you are really defining a delta between the new class and its parent class. In other words, a subclass definition is like a mixin definition.

Given that short description, it should come as no surprise that an abstract class (with a few restrictions) is itself a mixin. Here is an example of a Persistance mixin:

 abstract class Persistence {  
  void save(String filename) {  
   print('saving the object as ${toJson()}');  
  }  
    
  void load(String filename) {  
   print('loading from $filename');  
  }  
    
  Object toJson();  
 }  

Restrictions on mixin definitions include:
  1. Must not declare a constructor
  2. Superclass is Object
  3. Contains no calls to super
You can use the mixin with the with keyword. Here is an example:

 abstract class Warrior extends Object with Persistence {  
  fight(Warrior other) {  
   // ...  
  }  
 }  
   
 class Ninja extends Warrior {  
  Map toJson() {  
   return {'throwing_stars': true};  
  }  
 }  
   
 class Zombie extends Warrior {  
  Map toJson() {  
   return {'eats_brains': true};  
  }  
 } 

In the above example, both Ninja and Zombie extend from Warrior. This makes sense, they are both warriors, so the is-a relationship applies. All warriors can be persisted and loaded from a database, but this is purely behavior and the statement Warrior is-a Persistence simply doesn't make sense. Inheritance does not apply here, but we can use a mixin to inject the functionality.

 main() {  
  var ninja = new Ninja();  
  ninja.save('warriors.txt');  
    
  var zombie = new Zombie();  
  zombie.save('warriors.txt');  
 }  

A class that uses a mixin is also a member of the mixin's type:


 print(ninja is Persistence); // true!  


Mixins are fairly new to Dart, so they aren't widely deployed. We're curious to see how you use mixins. Let us know on the Dart mailing list, and please file any bugs you may encounter. Thanks!

Post a Comment

Popular posts from this blog

  • Sponsor:  Register today for  New Game, the conference for HTML5 game developers . Learn from Mozilla, Opera, Google, Spil, Bocoup, Mandreel, Subsonic, Gamesalad, EA, Zynga, and others at this intimate and technically rich conference. Join us for two days of content from developers building HTML5 games today. Nov 1-2, 2011 in San Francisco.  Register now ! This is the second article in a Box2D series, following the Box2D Orientation article. The Box2DWeb port of Box2D contains a nice example to show off the basics of integrating physics simulations into your web app. This post will provide a walkthrough of the example, explaining the high level concepts and code. First, let's see the example in action. The code for the above is open source and available on GitHub. It was adapted from Box2DWeb's example . Animating Before we look at Box2D, it's important to understand how the above simulation is animated. You might think setInterval or setTimeout is
    Keep reading
  • In which I port a snazzy little JavaScript audio web app to Dart , discover a bug, and high-five type annotations. Here's what I learned. [As it says in the header of this blog, I'm a seasoned Dart developer. However, I certainly don't write Dart every day (I wish!). Don't interpret this post as "Hi, I'm new to Dart". Instead, interpret this post as "I'm applying what I've been documenting."] This post analyzes two versions of the same app, both the original (JavaScript) version and the Dart version. The original version is a proxy for any small JavaScript app, there's nothing particularly special about the original version, which is why it made for a good example. This post discusses the differences between the two implementations: file organization, dependencies and modules, shims, classes, type annotations, event handling, calling multiple methods, asynchronous programming, animation, and interop with JavaScript libraries. F
    Keep reading
  • Angular and Polymer, sitting in a DOM tree, B-i-n-d-i-n-g. First comes components, Then comes elements, Then comes the interop with the node dot bind. Angular , a super heroic MVC framework, and Polymer , polyfills and enhancements for custom elements built on top of Web Components, can live harmoniously in the same app. This post shows you how to connect Angular-controlled components to Polymer-controlled elements via data binding. And we do it all in Dart . Angular and Polymer I get asked "Should I use Angular or Polymer?" a lot. My answer is, "Yes". That is, both libraries have distinct strengths, and you can use both in the same app. Polymer excels at creating encapsulated custom elements. You can use those custom elements in any web app or web page, regardless if that app is built with Angular, Ember, etc. Angular excels at application engineering, with dependency injection, end-to-end testability, routing, and services. Here are som
    Keep reading