SwiftSuspenders 1.5, or: A tale of robots and refactorings

ActionScript,Projects,swiftsuspenders — till on May 15, 2010 at 17:41

Nearly half a year ago, I released SwiftSuspenders 1.0.

As hinted at in the related blog post, this new release contains a solution to the “Robot Legs Problem”: and it goes by the name of Child Injectors.

So, why would robot legs pose a problem for a dependency injection container, you ask. In short: They don’t – their creation does. See, DI containers are all about creating object graphs. That is: They allow you to create complex, nested trees of objects in an automated fashion.

Want to build a car? You can either go about it manually from the outside in: You create the car’s shell, then you realize that your car probably needs an engine. You put that in, at which point you realize that your engine will need need cylinders, so you add some of those, and so on.

Or, you can use a DI container and do everything the other way around: You first create a collection of all the parts your car will consist of, and then you tell the DI container to instantiate the outermost part – the shell. The container inspects the shell and sees that it needs some parts, like an engine. It then looks through the set of parts you supplied, and adds those that fit the dependencies of the shell. In doing so, each of the parts is itself inspected and all its dependencies are fulfilled, recursively.

Now, imagine you want to build a robot. Robots aren’t really special in any way that’s interesting for DI containers at all. It’s just that their construction is commonly used to explain a problem that you’ll sooner or later encounter if you use DI containers to create complex objects.

What is the Robot Legs Problem?

The robot legs problem describes the difficulties that one experiences when trying to construct structures with two or more sub-trees that are very similar, but not identical to one another.

See, that robot, it’s supposed to look like a human being in many ways: It’ll have a head, a torso, two arms and two legs. But there’s an important difference to a human: The robot is much, much simpler. For example, parts of this robot’s legs are identical for both sides. Now ideally, if you’ve got two knee joints that are entirely identical to one another, you only want to define them once. The problem is that for our robot, there are parts further down the legs that differ for each side. say the knee joints are identical, but the ankles are slightly different for each leg. How is the DI container supposed to know that it has to supply different parts somewhere down the leg if some intermediary parts are identical? It can’t. Well, not without some help, at least.

That’s the Robot Legs Problem.

There are (at least) two solutions to this problem: Either you add some differentiating attribute to the knee joints and all other parts that are really the same, functionally; or you somehow add information to the DI container’s configuration that lets it figure out the differences from the outside.

The first option isn’t really attractive, but it’s the easiest from a conceptual point of view: Instead of having one class Knee, you create two classes, LeftKnee and RightKnee, both extending Knee. The only thing that differs for these classes is that they define dependencies for LeftAnkle and RightAnkle respectively (I’m leaving out any intermediary parts such as bones here for reasons of simplicity. For your own, real-world, robot, you’d probably want to have some of those). Apart from adding a lot of boiler-plate code (imagine this with your real-world robot that has about 53 parts in each leg that are functionally entirely identical for both sides!), this creates serious problems in terms of separation of concerns and encapsulation: If the knees truly are functionally identical, it’s none of their business to know anything about which leg they are added to.

What kind of solution does SwiftSuspenders provide?

Obviously, we want to use the second solution – and with SwiftSuspenders 1.5, we finally can. The solution comes in the form of child injectors.

Child injectors are simple things: They try to satisfy all dependencies themselves, but if they can’t find a mapping for one, they turn to their parent and ask if it has a corresponding mapping. Really, they’re kinda dumb.

But here’s the thing: SwiftSuspenders lets you create trees of dependency mappings that use different child injectors to satisfy recursive dependencies. In our example, you’d create rules for the LeftHip and the RightHip:

var injector : Injector = new Injector();
var leftHipRule : InjectionConfig = injector.mapClass(LeftHip, LeftHip);
var rightHipRule : InjectionConfig = injector.mapClass(RightHip, RightHip);

Now in order to differentiate further down the leg, we create parallel structures for both legs in separate injectors. But first, we need to create and set these injectors:

//let your main injector create a child injector:
var leftLegInjector : Injector = injector.createChildInjector();
//you can also create a new injector and set its parent:
var rightLegInjector : Injector = new Injector();
rightLegInjector.setParentInjector(injector);
//Let SwiftSuspenders use the child injectors from the hip on down the leg:
leftHipRule.setInjector(leftLegInjector);
rightHipRule.setInjector(rightLegInjector);

With this, our injectors are all set up as we need them – on to the remaining injection mappings.

Both LeftHip and RightHip have a dependency (and I’m leaving out the knee here

[Inject] public var knee : Knee;

As this dependency is the same in both legs, we can safely add it to the main injector:

injector.mapClass(Knee, Knee);

Upon not finding a rule for the Knee dependency, the child injectors will turn to their parent and get the rule we just defined. After using that to inject the Knee, they will continue on down the tree of dependencies.
The Knee has a dependency for an Ankle:

[Inject] public var ankle : Ankle;

Not that the Knee would care, but this field is actually supposed to contain a different value, depending on which leg the Knee is added to! Because of that, we have to add different mappings to the child injectors:

leftLegInjector.mapClass(Ankle, LeftAnkle);
rightLegInjector.mapClass(Ankle, RightAnkle);

And with that, we’re done with the configuration! Assembling our robot is now a simple matter of letting our injector instantiate the class Robot, which of course defines dependencies for LeftHip and RightHip:

var myRobot : Robot = injector.instantiate(Robot);

Great! And what about the refactorings?

Right, the refactorings. Those have been applied to the SwiftSuspenders source code. Lots of them, in fact. Their primary goal was to support child injectors, but they also lead to a much cleaner separation of concerns. Basically, there are now three basic building blocks in SwiftSuspenders, each with their own very specific concern:

  • The Injector, which acts as the facade to the entire system and keeps everything together
  • The InjectionConfig, which acts as the broker between injection points and injection results
  • Several kinds of InjectionResults, which are held by InjectionConfigs and generate or keep the value that’s injected into injection points

In the future, robotic beings will rule the world. Well, that, and the aforementioned refactorings will allow for a better syntax for defining inection mappings. Something along the lines of injector.map(MyInterface, 'named').toClass(MyClass);. But that’s going to happen in the year 2000. Or version 2.0, I’m not sure.

Announcing SwiftSuspenders 1.0

swiftsuspenders — till on November 24, 2009 at 21:59

The History

Almost exactly two months ago, I announced the first public version of SwiftSuspenders, my DI/ IoC solution for AS3.

In that announcement I proposed that SwiftSuspenders might be finished and probably wouldn’t receive many changes anymore. Well, as it turns out, that was ridiculously wrong. Starting with version 0.8.1, the Robotlegs framework bundled SwiftSuspenders and as of Robotlegs version 0.9.1, it’s the only bundled DI solution, with adapters for other solutions available in their own github projects.

The Contributions

Combined with a huge increase of popularity of Robotlegs, this caused a constant influx of not only demands for features and bugfixes in SwiftSuspenders, but also design feedback and substantial contributions from Shaun Smith, Joel Hooks and Robert Penner.

The Release

Based on this feedback and in large parts thanks to these contributions, I’m happy to announce the release of a much improved SwiftSuspenders 1.0!

Contained in this release are many improvements over my initial beta release:

  • setter injection
  • method and constructor injection with optional arguments
  • [PostConstruct] metadata annotations, allowing method invocation after the injection process completed
  • XML configuration of injection points, enabling developers to use SwiftSuspenders in Flash Pro, which doesn’t support custom metadata
  • Injector#mapRule, enabling mapping multiple requests to the same response configuration
  • much improved unit tests
  • countless bugfixes
  • an even cleaner codebase

The Future

As outlined in this thread in the Robotlegs discussion group, I’m planning to tackle the “robot legs” problem next (for which I can’t seem to find a good explanation anywhere – links are much appreciated!)

I hope to get that done pretty quickly, so a 1.1 release might not be too far off.

Improved reflection support in Flash Player 10.1?

ActionScript — till on November 22, 2009 at 1:23

describeTypeJSON

So it looks like Flash Player 10.1 might support a somewhat improved reflections API containing support for:

  • retrieving reflected information as JSON (or rather, as an AS3 object tree)
  • filtering the request to only retrieve certain types of information
  • Some more functions that are used internally to construct the result of describeType

In other words, it containes improved access to the information available through describeType and nothing more.

All of this functionality resides in the avmplus package in the playerglobal.swc that can be downloaded from labs.adobe.com.

This package contains a few methods and an assortment of constants:

reflection-in-fp-10_1

The most (or only, really) interesting of these is DescribeType.describeTypeJSON. Using this method, it’s possible to retrieve reflection data as an object and to filter certain types of information using the constants seen in the image above as bit flags. For example, to get only information about the reflected classes constructor, you use the following code:

DescribeType.describeTypeJSON(TargetClass,
	avmplus.INCLUDE_CONSTRUCTOR |
	avmplus.INCLUDE_TRAITS | avmplus.USE_ITRAITS);

Using the different flags, it’s possible to request an object containing exactly the information needed for a certain use-case. For example, in SwiftSuspenders, I’d use the following code to get information about a types’ methods, getters/setters, variables and constructor, all with associated metadata:

DescribeType.describeTypeJSON(TargetClass,
	avmplus.INCLUDE_CONSTRUCTOR |
	avmplus.INCLUDE_METHODS |
	avmplus.INCLUDE_VARIABLES |
	avmplus.INCLUDE_ACCESSORS |
	avmplus.INCLUDE_METADATA |
	avmplus.HIDE_OBJECT |
	avmplus.INCLUDE_TRAITS | avmplus.USE_ITRAITS);

The last two flags have to be present to get any meaningful information at all. I honestly have no idea why it’d be necessary to explicitly state that, yes, I want to include traits – you know, the mechanism with which the virtual machine links everything to classes and without which a class is completely uninteresting. And don’t get me started on what avmplus.USE_ITRAITS stands for.

All of this can also be used with the new avmplus.describeType, which is essentially identical to flash.utils.describeType except that it adds an additional parameter for the configuration flags:

describeType(target : Object, flags : uint) : XML

Detours

If you think that that’s all you need to know about how to use this new API, think again. All of these methods and the DescribeType class are implemented as internal types of the avmplus package and thus not accessible from outside this package. Fortunately, this can be worked around by creating a public wrapper in the same package:

Is it all just a mistake?

There are some things that are a bit fishy about this whole affair: Why is all this functionality internal to the avmplus namespace? And what’s with the name “avmplus” in the first place? Seems like a weird choice to expose the project name of the VM in such a way. Also, the API feels quite rough and exposes functionality that’s seemingly useless to AS3 developers.

Investigating some more, I discovered how this entire API came to be: It’s the new implementation of the old describeType functionality in the new version of the ActionScript Virtual Machine, code named Tamarin Tracing. The log message of the commit which added it sheds some light on this. Since this initial commit, a few changes have been made, resulting in the current version of the API as exposed in 10.1 beta.

Now here’s my guess about what’s happened: When creating the Flash Player beta, some configuration option was set the wrong way, causing the avmplus package to be visible within playerglobal.swc, when it really should be an invisible implementation detail. At the very least, the API in this state probably isn’t meant for public consumption and might well be removed in the final 10.1 version.

Now what?

I’d really like for this API to stay – be it in the current state or as a polished version located in the flash.utils package or wherever. Unfortunately, I’m not sure what to do to that end; Adding a bug to the Flash Player issue tracker to ask that something that’s available in the beta should stay that way in the final release seems odd.

Introducing SwiftSuspenders

Projects — till on September 21, 2009 at 16:20

Working with RobotLegs

Recently, I started working with the awesome MVCS framework RobotLegs by Shaun Smith.

As I’m not a big fan of the configuration overhead that the Spring framework for Dependency Injection brings with it, I immediately fell in love with the metadata based SmartyPants IOC framework. While I really like the approach and everything worked great, I quickly realized that SmartyPants has two problems: It’s somewhat slow and, due to some dependencies on the Flex framework, rather big.

SwiftSuspenders: A fast, lightweight DI solution

That’s why I started implementing an ultra lightweight DI framework (which hardly even deserves being called a framework) which then became SwiftSuspenders.

SwiftSuspenders implements exactly the functionality needed by RobotLegs, nothing more, but, crucially, nothing less – and it does so as fast and as lean as possible. By focusing on these needs, I was able to implement a solution that’s about an order of magnitude faster and weighs only 10% of SmartyPants file size-wise. And yes: Both of these values are SWAGs and shouldn’t be relied on for, well, anything.

Right after I published SwiftSuspenders on GitHub – as you should do with everything you build that might be of help to your esteemed colleagues – awesome stuff happened: Shaun Smith immediately forked to project, started fixing bugs and embarrasing mistakes in the documentation and switched most of the examples for RobotLegs to using SwiftSuspenders and hinted at creating unit tests – which I shamefully neglected. Yesterday, he followed up on that and pushed a range of unit tests to a new GitHub project!

What now?

Apart from you reading the introductory documentation, starting to use SwiftSuspenders and forking it on GitHub? I’m not sure.

I think that maybe, SwiftSuspenders is pretty much done as it is. SmartyPants still has some features that SwiftSuspenders doesn’t, but for now, I don’t think that those are really essential. Then again, I might implement Provider Binding and Rule Binding sometimes later – whereas I can almost guarantee that I won’t implement live bindings.

On finding Unicode ranges

tools — till on June 6, 2009 at 20:14

Most people don’t think in code points – which seems like a pretty good state of the world to me.

The only downside is that dealing with fonts for Flash applications and sooner or later the whole web is far more complicated than it would otherwise be. Let me explain.

Each time your client requests you use their corporate typface or your designer decides that he absolutely, positively can’t use a web-safe font for some other reason, you have to somehow get font glyphs to the user that he doesn’t already have installed on his machine. In html, this is mostly done using png’s, increasing the download time and the complexity of changing the content. But at least for Flash you can instead embed the glyphs and keep your content as text. How do you do that? You embed the font in your swf and let the Flash player use it to render the content.

Now what you don’t want to do is embed the whole font, because that’ll add between several dozen kb and several mb (no kidding!) to your swf. Instead, you’ll want to embed only the glyphs you need to display your content. And this is where Unicode code points come into the picture: You need to use those to tell the compiler which glyphs to embed.

To make a long story short, you’ll have to find out which Unicode ranges to use to make the compiler embed the glyphs you need. And for that, I’ve written a small JavaScript tool, which allows you to enter ranges of characters or just a bunch of text, which it then converts into an optimally reduced set of Unicode ranges.

You can find this tool here, I hope you find it useful and not too ugly.

Introduction

personal — till on June 6, 2009 at 18:39

To the world at large and you who is reading this in particular: Hello!

As seems pertinent for an introductory blog post, let me tell you a little bit about myself and what you can expect to read here in the future.

I am a web developer mostly concentrated on solving highly technical, rather abstract problems using ActionScript and other front end web development technologies. That is to say: I’m a Flash developer, but in contrast to many of my peers, I’m not too interested in fancy animations and gratuitous effects. Thus, I’m drawn not the quickly built, glossy high end projects that dominate the Flash world but to the invisible technical challenges that lie behind each well-built site or application.

I constantly re-evaluate my views on what is a good balance between pragmatism and theoretical soundness in my daily work, trying to stay on the right side of the boundary between writing maintainable code and becoming an architecture astronaut.

For the last two and a half years, I’ve lead the Flash development team at Fork unstable media. Before that, I worked as a freelancer for about seven years and studied philosophy and an ever-changing assortment of minor fields.

As of July 2009, I will be a co-founder of a yet-to-be-named startup located in Hamburg, Germany. What are we going to do? Mostly two things:
1. Work as a technical sub-contractor for for internet agencies, concentrating on websites, applications and presentations mostly done in Adobe Flash.
2. Try to cross the chasm that lies between the proprietary world of Flash and the standards-based rest of the web-universe.

Should you decide to return, I’ll tell you a lot more about this second aspect of what we’re going to do and about why I think that we’re going to fill an important niche.

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. | Till Schneidereit