Dependency Injection for Testability

My latest venture in improving my code has been incorporating the concept of Dependency Injection. In general, the overarching idea has to do with the the law of demeter. That is, the objects of my application should only collaborate or call actions on objects they use directly. For example, rather than passing a reference to a "service locator" or more commonly a shell or application class in Actionscript:
protected var loader:ILoader;
LoadedSWF(app:IApp)
{
    loader = app.getLoader();
}
I would say something like this instead:
protected var loader:ILoader;
LoadedSWF(loader:ILoader)
{
    this.loader = loader;
    ...
    (maybe queue up some thumbnails at this point)
}
The end goal is to have an object which only requires it's collaborators. There's no reason for this loaded swf to know about the app at large; suppose we want to drop it into another application context that simply isn't built within our "app framework?"

Miško Hevery recently gave a talk on this, which I've linked here at the end of the post. Some great points to note:

  • Object instantiation should be abstracted to factories to wire up your application. You can group factory logic together based on what the object lifetimes are of what they create. You might create a factory for compile time objects, runtime (usually loaded swfs) or service lifetime. With each case you only want to inject an object in the constructor that has a lifetime greater than or equal to the injectee.
  • One of the best examples given is when you're purchasing something, do you give the clerk your wallet or the cash? In the same way, you should give your objects what they need directly instead of massaging data.
Here are the tubes:

I'll be posting more on this topic later as it relates specifically to Actionscript.

A New Look

And here’s the new look. It’s obviously not complete yet, but I just wanted to get something up to replace the standard template and to have something to call my own. There are still a few kinks to work out to get it to validate, but it does boast some nifty features.

The color template for this page is generated using Adobe Kuler. I randomly select a word out of the set ["zen", “ocean”, “mist”, “pea”, “grasshopper”, “kiwi"], then organize the colors from lightest to darkest so I can assign them dynamically to different CSS classes defined like ["lightest", “light”, “mid”, “dark”, “darkest"]. If the colors are hideous or unreadble, just reload the page. I’m working on some color normalizations that will increase the contrast between the colors if the difference is below a certain threshold, ie, text on a colored background becoming unreadable.

Another cool feature is auto-linking. Since I’m a programmer, I’m naturally lazy by trade, and I don’t want to find the URL of whatever I want to link to since Google can do it better. So instead of finding the Wikipedia article to “Test driven development”, I can just say something like this:

Test driven development
This will trigger some javascript to automatically grab the first result from Google and then link it within my page. I’m planning on adding some additional features to inject additional kewords w/o effecting the link label, i.e., adding the word “wiki” to the end of the query w/o the resulting link having “wiki” in the label.

If you follow the development of this blog, I’ll be posting the source as I go along-- but for the eager I’d just sniff the traffic to check out any of my JS files smile.

Using Enums In AS3

Using the enum strategy can save you some heartache if you want to create type safe applications. Say you have a type characteristic of an object. For example, every time you create a new Person(), you can specify a height like new Person("tall"), new Person("average") or new Person("short"). But how do you ensure that you aren't saying new Person("some height that isn't supported")? In the past what I've done, is create a separate class that only contains constants that are valid heights.
public class PersonHeight
{
    public static const TALL:String = "tall";
    public static const AVERAGE:String = "average";
    public static const SHORT:String = "short";
}
Although this allows me to change what the actual values of these constants are easily throughout the app, it still doesn't give me type safe checking to say whatever I pass into new Person(height:String) is valid or not. By simply modifying how we are specifying our height constants, we can do better than passing in a generic string.
public class PersonHeight
{
    public static const TALL:PersonHeight = new PersonHeight("tall");
    ...
    public var value:String;
    
    public function PersonHeight(value:String)
    {
         this.value = value;
    }
}
Now in my person class, I can use the PersonHeight as a type and not just as a container for constants.
new Person(height:PersonHeight)
Et voila! A type safe parameter. Obviously this is only the tip of the iceberg, but since this is a recent discovery for me, I think it's awesome and allows me to geek out even more than I normally would wink

Yet Another Blog Engine

From Blogger to Chryp and now Expression Engine! This page will be changing a ton in the next few days as I migrate over, but I think this one is for keeps.

Math Mod Util Class

In most programming languages (or Actionscript at least), they use the computational definition of mod where it simply is the remainder of the first operand divided by the second. This works fine for n % m where n, m are elements of N. However, for -3 % 4, the computation looks something like this:


for n % m, n = -3, m = -4:
-3 / 4 = -.75
-.75 * 4 = -3
so -3 % 4 = -3

The mathematical definition of mod says for n mod m, where n is an element of Z, and m is an element of N, the result of n mod m is in the range [ 0, m - 1 ]. So -3 mod 4 = 1. This is a simple fix for Flash’s % operator. The code below is in AS2, but the AS3 version is essentially the same (maybe you would ensure n, m are ints):

public static function mod(n:Number, m:Number):Number
{
    var tmp:Number = n % m;
    return tmp < 0 ? tmp + m : tmp;
}

This is great for implementing a circular array, say for a nav where you can press left + right keys and when you get to the first element and press left, you go to the last nav element ( n - 1 if n is the length ). So for your leftKeyHandler function you can just do something like this instead of checking if index == -1, index = length - 1:

function leftKeyHandler():Void
{
    selectNav(MathUtil.mod(--index, navElements.length)); 
}