ArrayCollection: filterFuntion with multiple filter functions using decorator pattern

I was looking for an elegant solution to implement multiple filter functions on an ArrayCollection (which provides a method filterFunction() that can be assigned dynamically in order to filter data inside the collection). The first and only valid solution I found was that one from Cristian Rotundu, he has extended ArrayCollection class providing a filterFunctions properties which accepts an Array of functions which will be executed in sequence (into a loop) once filterFunction is triggered. Anyway I didn’t want to subclass ArrayCollection and by using the decorator pattern I implemented my own multiple filters version.

So, this is what I done:

  1. I defined an interface IFilter, which declares only one method: apply()
  2. I defined a dummy Filter class (which implements IFilter in a basic way just to agree to the interface), that is used as a basic empty filter to decorate. It also has a constant called ALL_VALUES which is used as a wildcard for filters (it’s a simple string with value “*”, which means “all values are allowed”)
  3. I defined an abstract AbstractFilterDecorator class
  4. I created as many subclass of AbstractFilterDecorator as the filters I need (yes I treat filters as classes not mere functions)

The implementation code is the following:

var data:ArrayCollection = ArrayCollection(grid.dataProvider);
var filter:IFilter = new Filter();
filter = new LevelFilter(filter, levelValue);
filter = new CategoryFilter(filter, categoryValue);
filter = new DateFilter(filter, dateValue, "DD/MM/YY");
data.filterFunction = filter.apply;

The filter object is wrapped by decorators which all accepts 2 common arguments: an IFilter reference and an Object representing a value. The DateFilter has a third parameter which is used to configure an internal DateFormatter (from mx.formatters package).
I’m pretty satisfied :)
Uh… and if you are worried about performance, it is fast enough because filter object are created once and then the function assigned to filterFunction is a reference to the resulting decorated filter.

I realized a very simple example application which can be downloaded here.
This following is the content of the mxml file:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" layout="vertical">

			import mx.collections.ArrayCollection;
			import com.daveoncode.filters.*;
			private function applyFilters():void {
				var data:ArrayCollection  = ArrayCollection(userGrid.dataProvider);
				var filter:IFilter = new Filter();
				filter = new AgeFilter(filter, ageFilterValue.text);
				filter = new DateFilter(filter, dateFilterValue.selectedDate);
				filter = new SexFilter(filter, sexFilterValue.value);
				data.filterFunction = filter.apply;
	<mx:Panel title="Filters" width="600">
			<mx:FormItem label="Age:">
				<mx:TextInput id="ageFilterValue" width="30" />
			<mx:FormItem label="Sex:">
				<mx:ComboBox id="sexFilterValue" dataProvider="{[{data: Filter.ALL_VALUES, label: 'ALL'}, {data: 'm', label: 'Male'}, {data: 'f', label: 'Female'}]}" />
			<mx:FormItem label="Join date:">
				<mx:DateField id="dateFilterValue" formatString="DD/MM/YY" />
				<mx:Button label="Apply filters" click="{this.applyFilters()}" />
	<mx:Panel title="Users" width="600">
		<mx:DataGrid id="userGrid" width="100%">
						<mx:Object age="24" sex="f" name="Susan" joinDate="{new Date(2007, 5, 15)}" />
						<mx:Object age="36" sex="f" name="Ashley" joinDate="{new Date(1998, 7, 20)}" />
						<mx:Object age="24" sex="f" name="Jennifer" joinDate="{new Date(2001, 3, 24)}" />
						<mx:Object age="19" sex="f" name="Emma" joinDate="{new Date(2002, 3, 24)}" />
						<mx:Object age="44" sex="f" name="Carol" joinDate="{new Date(1999, 9, 16)}" />
						<mx:Object age="28" sex="m" name="Peter" joinDate="{new Date(2005, 3, 12)}" />
						<mx:Object age="35" sex="m" name="Mike" joinDate="{new Date(2008, 10, 10)}" />
						<mx:Object age="26" sex="m" name="Dave" joinDate="{new Date(2008, 10, 10)}" />
						<mx:Object age="44" sex="m" name="William" joinDate="{new Date(2004, 9, 16)}" />
						<mx:Object age="24" sex="m" name="Sean" joinDate="{new Date(2006, 3, 24)}" />

Learning design patterns with Actionscript 3: episode 2 – Decorator pattern

The objective of the decorator pattern is to provide a way to add extra features and responsibilities to a class at runtime without to subclass it.

The classes diagram of this pattern is composed by an interface or an abstract class which will define the supertype of the class that will be extended (decorated) by one or more classes implementing the same interface and extending an abstract class which identify these as decorator classes.

A real scenario into which apply this pattern can be a cars store. A car is the base class and the accessories such dvd player, gps, air conditioning and so on, can be thought as decorators. Once decorated, the car (which has a method getPrice() which returns its cost) will get updated by accessories, so calling the getPrice() method will include the price of the “naked” car plus the price of the various accessories installed.

Let’s take a look to the classes…

package com.mycarstore {
    public interface IVehicle {
        function getPrice():Number;
        function getDescription():String;

The interface above will be implemented by all the classes and we will treat the car as an IVehicle not a concrete Car class.
This is our simple Car class:

package com.mycarstore {
    public class Car implements IVehicle {
        public function Car() {

        public function getPrice():Number {
            return 50000;
        public function getDescription():String {
            return "Base car";

Now is time to see the decorators (in our scenario the accessories). This is the abstract Accessory class, all accessories will extend it:

package com.mycarstore {
    public class Accessory implements IVehicle {
        protected var _vehicle:IVehicle;
        public function Accessory(vehicle:IVehicle) {
            this._vehicle = vehicle;
        public function getPrice():Number {
            return this._vehicle.getPrice();
        public function getDescription():String {
            return this._vehicle.getDescription();

In Accessory we can notice that the class encapsulate an object of IVehicle which is passed to the constructor (of course since this class is abstract the object will be passed to the constructor of Accessory’s subclasses). This is the key concept of decorator pattern, all decorators keep a reference of the interface they are going to decorate and this reference is used as the base for methods business logic. Let’s see how:

package com.mycarstore {
    public class DVDPlayer extends Accessory {
        public function DVDPlayer(vehicle:IVehicle) {
        override public function getPrice():Number {
            return this._vehicle.getPrice() + 550;
        override public function getDescription():String {
            return this._vehicle.getDescription() + ", DVD Player";

DVDPlayer is a concrete decorator and it uses the encapsulated IVehicle object in order to provide an extended version of the interface methods (getPrice() and getDescription()). Basically it uses first the reference methods and then it adds some other values.

To use the pattern we will first instantiate a Car object, than we will wrap it with one or more decorators:

var car:IVehicle = new Car();
trace("Price: " + String(car.getPrice()) + " - description: " + String(car.getDescription()));
car = new DVDPlayer(car);
trace("Price: " + String(car.getPrice()) + " - description: " + String(car.getDescription()));
car = new GPSSystem(car);
trace("Price: " + String(car.getPrice()) + " - description: " + String(car.getDescription()));

The output will be:

Price: 50000 - description: Base car
Price: 50550 - description: Base car, DVD Player
Price: 50875 - description: Base car, DVD Player, GPS System

The order into which we wrap the concrete component (Car) is indifferent (we can add GPSSystem before or after DVDPlayer) and of course despite its readability, we can wrap the Car in a single statement:

var car2:IVehicle = new GPSSystem(new DVDPlayer(new Car()));

In this example I used very simple classes, however in a real implementation we can create more sophisticated decorators which will accept extra arguments beyond the IVehicle reference.

Set DataGridColumn’s width in percentage with ease

I was trying to set the columns of a DataGrid to a certain percentage, but I discovered that inexplicably DataGridColumn doesn’t provide percentageWidth property nor it accepts a percentage string as width property… so I did a quick search on google and I found that is sad but true and moreover the solution I found on the web is to use a function to calculate each single column width after creationComplete event is dispatched… terrible! However I did a test before, by assign a decimal value to width (0.5 instead of 50%) and it works! The width property in fact accepts a Number as value not an int, so we can specify a value under 1, which is treated as a percentage… what surprise me, is that no one seems to had this idea… anyway I hope this will be helpful for all.

This is a piece of my AS code to set DataGridColumn width in percentage:

col = new DataGridColumn();
col.width = options[i] == "Message" ? 0.6 : 0.1;

In my code I’m setting the columns to 10% and to 60% only for “Message” column.

parseInt(): difference between Javascript and Actionscript

Today is the day of the little big discoveries. I realized that the parseInt() function, which objective is the same in both languages (Actionscript and Javascript), is a bit different between them. In Actionscript the function is based on base 10 numeration, in Javascript instead the funny thing is that it try to guess the radix by analyzing the string received as first argument, so if you want to be sure of the result returned you have to explicitly pass the radix in the second argument.


var myString = "000123";

The code above will alert 83 instead of 123 (because the default base guessed by Javascript isn’t 10 like in Actionscript), to get 123 the code must be:

var myString = "000123";
alert(parseInt(myString, 10));

Aptana’s Javascript editor is too cool!

I’ve just discovered that the last version of the Aptana Studio (in my case the Eclipse plugin version) has an integrated support for javadoc syntax inside js files. The beauty of this feature is that, once you have defined a function, you can just type /** and press enter and Aptana will generate automatically all the comments for you:


Furthermore it will show tips including parameters description when you will use your previous defined function:


…and if you want to add extra “@tag”, the editor will suggest you all tags available:


Too cool!!! I love Aptana :-)