Juten Tach,
lately i came across the || operator again and i read through the language specification. Little quiz: What is the content of the variable result in this line of code?
var result:* = null || "one" || "two";
The answer is: “one”. As for me, i had forgotten, that the || operator actually returns the value, that evaluates to true. If both values evaluate to true it returns the one on the left first.
So i started to think about, how to make use of this and the Chain of Responsibility Pattern came to my mind. You remember this pattern, right? You have a list of classes, that have different capabilities and you have a task. Instead of finding out by yourself, which class to use, you simply pass it to a chain, where these classes are connected. Each class determines for itself, if it is responsible and the first one, that answers with yes, is returned and gets the job.
So here i present a little exemplary implementation of a Chain of Responsibility, that in its core makes use of the || operator. By the way, i am not really conforming to the original pattern, because i actually don’t like it. In the original pattern, the potentially responsible classes link to each other directly, which in my opinion causes some trouble. First, they have to be aware, that they are part of a chain, which i think, they shouldn’t and second, they define the order in the chain themselves, which i think they shouldn’t and third, the requesting class has to know, which one is the first class in the chain, which i think, it shouldn’t.
[Caution]: This post now gets a bit lengthy
To build this Chain Of Responsibility thing, we need four ingredients: a chain, some potentially responsible classes, a request that should be processed and finally a using class, which wants the request to be processed.
We start with the request. For this example, it is really simple:
package responsibility {
public class Request {
public var stuffToBeProcessed:*;
}
}
As you can see, there is just a variable, which holds some kind of value, with which we want to work with. I did not give it a type to make it more interesting at runtime. You will see later on.
OK, next we need some classes, which can handle this type of request. Therefore we define an interface, which describes this general ability.
package responsibility {
public interface Responsible {
/**
* Checks, if this class can handle the request.
* @return An instance of Responsible or null.
*/
function checkResponsibility(request:Request):Responsible;
/**
* Processes the request.
*/
function doIt():void;
}
}
Pretty easy, right? The checkResponsibility(request:Request) method will either return itself, if it feels responsible for the request or null. The doIt() method then will actually do, whatever is to be done for fulfilling the request.
Next, we have two concrete classes, which implement this interface, ResponsibleOfStrings and ResponsibleOfNumbers:
package responsibility {
public class ResponsibleOfStrings implements Responsible {
public function checkResponsibility(request:Request):Responsible {
if(request.stuffToBeProcessed is String) {
return this;
}else return null;
}
public function doIt():void {
trace("ResponsibleOfStrings is doing it!");
}
}
}
package responsibility {
public class ResponsibleOfNumbers implements Responsible {
public function checkResponsibility(request:Request):Responsible {
if(request.stuffToBeProcessed is Number) {
return this;
}else return null;
}
public function doIt():void {
trace("ResponsibleOfNumbers is doing it!");
}
}
}
So, you can see, these classes simply check if the request holds a string or a number respectively. If they find what they expect, they return themselves, otherwise they return null.
OK, next we need a chain. Very well, here it is:
package responsibility {
public class ChainOfResponsibility {
private var listOfResponsibleObjects:Vector. = new Vector.;
public function addResponsibleObject(responsibleObject:Responsible):void {
listOfResponsibleObjects.push(responsibleObject);
}
public function determineResponsibleObject(request:Request):Responsible {
var result:Responsible = null;
for(var i:int = 0; i < listOfResponsibleObjects.length; i++) {
result ||= listOfResponsibleObjects[i].checkResponsibility(request);
}
return result;
}
}
}
So finally here comes the part with the || operator. We run a list of potentially responsible classes. And in the function determineResponsibleObject(request:Request), we now go through this list. And here we make use of the fact, that when we chain the return values of each checkResponsibility(request) call by using the || operator, we get the first one, that returned itself instead of null. Means, we get the first class instance, which feels responsible for doing the job.
OK, lastly of course, we want to see, how to use that stuff. So here it is:
package {
import flash.display.Sprite;
import responsibility.*;
public class Main extends Sprite {
public function Main() {
var chainOfResponsibility:ChainOfResponsibility = new ChainOfResponsibility;
chainOfResponsibility.addResponsibleObject(new ResponsibleOfNumbers);
chainOfResponsibility.addResponsibleObject(new ResponsibleOfStrings);
var request:Request = new Request;
request.stuffToBeProcessed = 10;
var responsibleObject:Responsible = chainOfResponsibility.determineResponsibleObject(request);
responsibleObject.doIt();
}
}
}
So, first we are setting up our Chain of Responsibility an give it our two responsible classes. Then we build a new request. In this case, we assign a number to the variable stuffToBeProcessed. Then we hand that request over to our chain and save the result in our variable responsibleObject. Finally we call the doIt() method on that object. And if we run this, we get a trace saying “ResponsibleOfNumbers is doing it!”, as expected. Of course, if we had assigned a string to the variable stuffToBeProcessed, than we would have seen “ResponsibleOfStrings is doing it!”.
Well, that’s it. If you find this useful, you can use it freely for any purpose.
Juten Tach,
it is a common procedure for me to visit the websites of the people, who leave comments on my blog. And what can i say, this time it payed off very well. On http://actualwave.com/blog/ (caution: this one is in Russian), after some Google Translation, i could find two very interesting links to tools for Actionscript:
- UML4AS is a UML editor plug in for Eclipse, which directly syncs with your ActionScript code and vice versa. Still alpha, but already very promising.
- Realaxy is actually, what i am thinking about for some time now. It is an Actionscript editor based on the MPS editor toolkit from Jetbrains, which means, it is based on an abstract syntax tree, instead of code text files. So far, there are only screencasts to watch, but still, very, very interesting.
Juten Tach,
i work with Actionscript for some time now, but i wasn’t aware of that little thing. You can use “in” for checking, if an attribute/field exists in an object, like so:
package {
import flash.display.Sprite;
public class Test extends Sprite {
public function Test() {
var myObject:Object = {name: "foo", nothing: "bar"};
trace("name" in myObject); // true
trace("anything" in myObject); // false
}
}
}
It also works for checking for fields in class instances. Might come in handy sometime
Juten Tach,
i already wrote about this a while ago, but now i have filed a feature request in the bug base of Adobe. I want const fields allow for being initialized in the constructor, too, not only inline. Here’s, what i wrote in the ticket:
hello,
in the AS3 specification it says:
“A variable declared with the const rather than the var keyword, is read-only outside of the variable’s intializer if it is not an instance variable and outside of the instance constructor if it is an instance variable. It is a verifier error to assign to a const variable outside of its writable region.”This implies, that a const can be initialized in the constructor, but in fact, it cannot, when in strict mode.
In the past, there have been at least two bug reports around this, with slightly different outcome. An early report (ASC-351) seemed to state, that it should be possible to initialize a const in the constructor. Unfortunately, from the report it is unclear, if strict mode was involved or not.
Another report later (ASC-3562) stated, that it would only be possible without strict mode.
I do think, that const initialization should be possible in the constructor, like the AS3 specification suggests, even in strict mode. It would make the whole const concept more useful. For example, declaring a const in a superclass and giving it a value inline currently means, that in subclasses you cannot give it a different value, because you cannot re-declare the field and you cannot give it a different value in the constructor.
Also, you might want to do some checks to decide which value to assign to the const, which you could do in the constructor based on parameters or other factors.
From my point of view, adding the ability to initialize a const in the constructor in addition to do it inline as currently possible, will not break any existing code, since it just adds new functionality, but does not change or take away existing functionality (besides not throwing a compile time error anymore).
So, what do you think? Do you agree? If yes, please vote for the feature request in the bug base. Otherwise, i still would be interested to read your opinion, of course
Juten Tach,
i know, everybody hates Singletons, and i do, too. But i find it an entertaining exercise to come up with new ways of circumventing the lack of private constructors for Singletons. Today this new one came to my mind:
First, we define an Interface, which specifies, how our Singleton should look like:
IMySingelton.as:
package {
public interface IMySingleton {
function doodle(something:String):void;
}
}
Ok, next we define our Singleton.
myInstance.as:
package {
public var myInstance:IMySingleton = new MySingleton();
}
class MySingleton implements IMySingleton {
public function MySingleton() {
trace("MySingleton is now there!");
}
public function doodle(something:String):void {
trace("yippee: " + something);
}
}
Very simple, isn’t it? We could optionally also go without the Interface, but then we loose code completion in our editors, because the class MySingleton will be ignored by most editors, although it would compile and run just fine. I do agree, that this is not really exactly the idea of a Singleton, because it has no getInstance() method, but in the end, the result is the same, we only have one global instance of MySingleton.
And since the variable is already global, we don’t even have to declare it in our class, we can directly use it:
Main.as:
package {
import flash.display.Sprite;
public class Main extends Sprite {
public function Main() {
myInstance.doodle("loodle");
}
}
}

