<![CDATA[Till Schneidereit]]> 2014-04-05T15:56:51+02:00 http://tillschneidereit.net// Octopress <![CDATA[On Brendan's Success]]> 2014-04-03T23:13:00+02:00 http://tillschneidereit.net//2014/04/03/on-brendans-success This Open Web thing? Brendan Eich spent the last 20 years helping to create, then save, then grow it. It might still exist in some meaningful form without him. It might not.

Brendan has stated his motivation for this work over and over again: to enable free speech. I’m sure he likes it better when that speech agrees with his own opinions. I know that he sees not just the freedom of speech but, more to the point, ways to efficiently disseminate all speech as transcending his personal opinions on almost all topics.

He succeeded fantastically well: the web is more open and better at facilitating speech than any other medium in the history of mankind. It is, as the EFF put it “one of humanity’s greatest accomplishments”.

Without this accomplishment, it’s highly unlikely that Twitter would exist – the communications platform that enables the quick formation of movements for a cause in a way that puts everything before it to shame.

Without this accomplishment, it’s highly unlikely that OkCupid would exist – the dating platform that “devoted the last ten years to bringing people—all people—together”.

Without this accomplishment, it’s highly unlikely Brendan would have resigned today.

To the extend that his resignation is a victory for the LGBTQ movement, it is a victory that Brendan played a key role in enabling.

Unquestionably, it is an impressive demonstration of the Open Web’s power. On his role in creating it, I want to congratulate Brendan, and thank him.

]]>
<![CDATA[Editing Git and Mercurial Commit Messages With Sublime Text 2]]> 2012-05-14T01:37:00+02:00 http://tillschneidereit.net//2012/05/14/editing-git-commit-messages-with-sublime-text-2 Not only is Sublime Text 2 a fabulous code editor – it also works very well as an editor for shell commands.

At least for me, a major use-case for invoking an editor from the shell is editing commit messages in Git and Mercurial. Now simply setting sub, the shell command for invoking Sublime Text 2, as Git’s or Mercurial’s editor won’t work for that: sub returns immediately instead of waiting for the commit message to be written and saved.

Enter sub --wait. With the --wait (or -w) argument, sub doesn’t return until the file has been closed. The beauty of it is that it’s not necessary to close the entire application: as soon as the sub-opened file is closed, sub returns and the terminal window is focused again!

Wow, cool! But how?

While I don’t know a thing about how sub does this, I do know how to set things to use it.

For Git, run the following command:

1
git config --global core.editor "sub --wait"

For Mercurial, edit the file ~/.hgrc and add the following line under [ui]:

1
editor = sub --wait
]]>
<![CDATA[Setting Up Eclipse CDT To Work On SpiderMonkey]]> 2012-05-09T14:01:00+02:00 http://tillschneidereit.net//2012/05/09/setting-up-cdt-to-work-on-spidermonkey Note: This text has since been added to MDN, so that version is very likely to be more up-to-date than this one, depending on when you’re reading this.

The version of Eclipse’s CDT that’s will be released with the next major release of Eclipse, codenamed “Juno”, has some pretty decent features that make it an attractive environment to work in.

Over at the Mozilla Developer Network, there’s a guide for setting up CDT to work with the Mozilla codebase. As that guide is a bit outdated and doesn’t cover setting things up for just SpiderMonkey instead of the whole Mozilla codebase, here’s a short-ish guide for doing just that:

Step 1 – Preparing a SpiderMonkey build

For CDT to index all code, SpiderMonkey has to be built with debug information. The full process of and requisites for doing so are described on MDN. Please follow those instructions up until the point of invoking configure.

I prefer building with clang, so my modified build commands look like this:

1
2
3
mkdir _DBG.OBJ
cd _DBG.OBJ
CC='clang -Qunused-arguments -fcolor-diagnostics' CXX='clang++ -Qunused-arguments -fcolor-diagnostics' ../configure --enable-debug --disable-optimize --enable-debug-symbols

Note: due to a bug in CDT, it’s currently not possible (or at least not straight-forward) to build with ccache. See Step 4 below for a workaround.

Step 2 – Installing Eclipse and Setting Up the Project

The following run-down is a condensed and updated version of what’s explained in much more detail on MDN for the entire Mozilla codebase. Luckily, improvements in CDT have reduced the basic process to a manageable 10 steps:

  1. Download and extract “Eclipse IDE for C/C++ Developers” from the Eclipse Developer builds
  2. Download the latest snapshot of the CDT from Eclipse’s CI server without extracting the contents
  3. Start Eclipse and create a workspace somewhere
  4. Select “Install New Software…” from the “Help” menu
  5. Click the “Add…” button in the upper right to add a repository, then click on “Archive…” and select the CDT snapshot (use “sd90-snapshot” or something similar as the name)
  6. Select “C/C++ Development Tools” from “CDT Main Features” and whatever you want from “CDT Optional Features” and click “Next” and agree to licenses and installing unsigned packages and all that jazz until you’re prompted to restart
  7. Restart Eclipse
  8. Back in Eclipse, select “New > Makefile Project with Existing Code” from the “File” menu
  9. Give the project a name you like (“SpiderMonkey” has a nice ring to it) and use the “Browser…” button to select your checkout’s js/src folder for the “Existing Code Location”
  10. Choose the correct toolchain for your platform (i.e. MacOSX GCC on Mac) and click “Finish”

At this point, the indexer starts running and already produces a pretty decent index of much of SpiderMonkey. Still, there are a quite a few things that CDT doesn’t pick up yet: For everything to be indexed, CDT has to be aware of the project’s build details.

Step 3 – Index All the Code

To let CDT know about the build, it has to invoke make itself (or, as is done in the guide for the whole Mozilla codebase on MDN, read a log of the build). This can be setup in another set of decently simple steps:

  1. Open the project’s properties by selecting its root and clicking “Properties” in the “File” menu and select “C/C++ Build”
  2. Under “Builder Settings”, deactivate “Use default build command”
  3. Instead, change “Build command” to read make -w (this is required because CDT needs detailed information about which directories make operates on, which using -w causes make to provide)
  4. Change the “Build location” to the build directory configured in step 1. For me, that means changing “Build directory” to read ${workspace_loc:/SpiderMonkey/_DBG.OBJ}
  5. Under “Behavior”, make sure that “Enable parallel build” is deactivated, as CDT’s indexer will freak out otherwise
  6. Remove “all” from “Build (Incremental build)”
  7. Deactivate “Clean” so that your builds don’t take ages
  8. If you’re using clang, a bug in CDT requires changing one more setting: in the project’s “C/C++ General –> Preprocessor Include Paths, Macros etc.” settings panel, select the “Providers” tab, then select “CDT GCC Build Output Parser” and change the content of the “Compiler command pattern” input field to read (gcc)|([gc]\+\+)|(clang)
  9. Start the build by selecting “Build All” from the “Project” menu
  10. Start the indexer by selecting “Index > Rebuild” from the project’s context menu

And that’s pretty much it: Large parts of SpiderMonkey should now be indexed. Unfortunately, there are also large parts that aren’t properly indexed, leading to errors and warnings being shown for perfectly valid code, but I find that the parts that do work do so nicely enough to make it totally worth it.

That leaves us with only one thing to do:

Step 4 – Speeding It Up

As mentioned above, CDT doesn’t like ccache for some reason. Until that bug is fixed, a somewhat simple workaround is to hide the usage of ccache by wrapping it with shell scripts for gcc/g++ and clang/clang++, respectively. I use clang, so I put two scripts into /usr/local/bin/:

cclang:

1
2
#!/bin/bash
/usr/local/bin/ccache /usr/local/bin/clang $@

cclang++:

1
2
#!/bin/bash
/usr/local/bin/ccache /usr/local/bin/clang++ $@

After a quick chmod u+x /usr/local/bin/cclang*, use the following configure command to start working with ccache after all:

1
CC='cclang -Qunused-arguments -fcolor-diagnostics' CXX='cclang++ -Qunused-arguments -fcolor-diagnostics' ../configure --enable-debug --disable-optimize --enable-debug-symbols
]]>
<![CDATA[On Beginnings]]> 2011-12-13T15:06:00+01:00 http://tillschneidereit.net//2011/12/13/on-beginnings On December 31, 1995, Calvin and Hobbes boarded their sled and took off into the blank canvas that to them was the stark white, freshly snow-covered scenery.

That’s not what this post is about. At least in part, it is, however, about endings. Just as that last comic strip Bill Watterson ever published.

In the fall of 1999, I discovered this fantastic little tool called Macromedia Flash 4. To cut a long and boring story short, the result was that instead of going to university, I immediately kicked off my career as a professional web developer in the advertising industry. While in hindsight, that claim of professionalism was bordering on the ridiculous in its utter optimism and naïveté, the good news is: it somehow worked and while I did start university a year later, it had to take a back seat to my main occupation.

Now, twelve years on, it seems like not that much has changed. Granted: I spent the last five years not only developing but also managing teams and doing conceptual work. Still, at the core of things, I am what I was all those years ago – a web developer.

As you might have guessed, though, the real changes are a bit more subtle. As time went on, I became more and more aware of two important facts: first, neither my talents nor my interests really lie in the frontend; second, twelve years of doing advertising is enough for a lifetime.

Don’t get me wrong: I don’t have any deeply-rooted problem with advertising in and of itself. I do, however, think that there’s a fundamental problem with projects in the advertising industry: they lack real stakeholders. Now I might be completely off the mark here, but that was my overarching impression in almost all the projects I was ever involved in and it makes a lot of sense to me, too: the companies you work for in advertising have their stakes in their products, not really in marketing them.

Whether I’m right about this doesn’t really matter, though: real or imagined, this gap I experience is enough of a problem for me that I want to change what I’m working on.

The other part of the equation is that I enjoy building systems, applications and frameworks, not microsites. The projects I enjoy the most are along the lines of Robotlegs, Swiftsuspenders and Reprise – an MVC framework, an IoC container and a CSS-based layout and components framework. Building a CMS abstraction layer to be used by the hundreds of agencies building modules and microsites for the NIVEA website was pretty neat, too.

For these reasons, I have decided to close my current business as the tech lead of a small team of sub-contractors to advertising agencies at year’s end.

As of January 2012, I will do some exploring of a blank canvas of my own and be available for bookings as a freelancing developer specialized in building systems, renderers and complex applications. I’m perfectly capable of doing and will do the occasional frontend programming if an otherwise perfect job requires it, but as said above, I strongly believe that my real talents lie a bit deeper down the stack. If that sounds like something your company could use and you’re either located in Germany or could include me working remotely then please do get in touch!

]]>
<![CDATA[Flash >= CS5 and version control: Of binary data and wasted bandwidth]]> 2011-10-23T17:05:27+02:00 http://tillschneidereit.net//2011/10/23/flash-cs5-and-version-control-of-binary-data-and-wasted-bandwidth With the advent of Flash CS5, Adobe switched the format of .fla files from the quirky binary format it was in previous editions to what every self-respecting developer of document-creation tools uses nowadays: A compressed archive consisting of an XML file (the actual document) and lots of additional files.

This in itself would be pretty nice, what with enabling third-party tooling and all. What I want to get at, though, is that they were nice enough to also enable working with those same documents saved as an uncompressed folder: Choosing Flash CS5 Uncompressed Document (*.XFL) as the file format when saving a project causes a folder with the project’s name to be created. Inside this folder is everything that would normally be contained in the .fla:

  • The file DOMDocument.xml, which is the equivalent of the .fla file without any embedded assets or settings
  • The file PublishSettings.xml, which contains exactly what you think it does
  • The file MobileSettings.xml, which also contains exactly what you think it does
  • The file META-INF/metadata.xml, containing the documents’s creation and change history
  • The folder LIBRARY, which contains the documents library, neatly structured in the same way as your library itself, but with additional folders for binary assets, such as BMPs
  • The folder bin, which contains cached versions of the binary assets, pre-converted to their output representations as compiled into the published SWF

The beauty of this setup is that you can work with all these different files just as you would with any other text or binary files: You can edit the XML files in your editor of choice, replace images with newer versions you get from your designer or use your diff and merge tools on them.

This last part is the most important to me: By replacing your .fla files with XFL folders, you allow them to be version controlled in a sane way. Instead of forcing your VCS to deal with incomprehensible blobs of binary data, hoping that it will make the best of it, you allow it to live up to all the hype about its efficiency and speed that caused you to use it in the first place.

One last tip on that: Use whatever means your VCS provides to exclude the *.dat files in the bin folder from versioning. They’re really simple caches that get re-created if missing.

]]>
<![CDATA[Mario Mushroom: Now with 80% less awesome]]> 2011-10-22T14:34:04+02:00 http://tillschneidereit.net//2011/10/22/mario-mushroom-now-with-80-less-awesome tl;dr: Don’t use the Mario Mushroom Operator if you don’t want your setter to be invoked more than once.

Update: I totally forgot to mention that I found out about this problem with @darscan while working on Swiftsuspenders and Robotlegs code.

The Details I think it was @robpenner who coined the term “Mario Mushroom Operator”.

In case you’re wondering, the Mario Mushroom Operator is this: ||=.

A good translation for how the MMO™ works seems to be this:

1
if (!field) { field = value; }

In case you’re still wondering, here’s how you’d use it:

1
2
function useRuntimeDefault(input:Object):void { input
||= getDefaultValue(); }

I.e., the most important use-case for the MMO™ is to apply runtime-determined default values for method arguments.

Now, that’s really useful and you might be wondering what could possibly go wrong with that.

Consider this snipped of code:

1
2
3
4
5
6
private var _setOnce : Boolean; private var _value :
Object;

public function set value(value : Object) : void { if (_setOnce) { throw new
Error('Value can only be set once'); } _setOnce = true; _value = value; }
public function get value() : Object { return _value; }

Used in a class, this code encapsulates a value that can be set exactly once, after which it can only be read.

With me still? Splendid.

In fact, you’re probably already guessing what comes now: Using the MMO™ to assign this once-settable value iff it hasn’t already been set:

1
value ||= {};

And here, finally, things go awry. As it turns out, the MMO™’s translation given earlier isn’t quite correct. Instead, the compiler (or the VM, I haven’t checked the bytecode) seems to translate our usage of the MMO™ to something along the following lines:

1
field = field ? field : {};

In summary, instead of guarding the assignment to a field as an if statement would do, the MMO™ only chooses between two values to use in the assignment like the ternary operator does.

In case you’re now thinking that that doesn’t affect you because you, just as every sane person you know, don’t ever have use-cases for one-time assignable fields, ask yourself whether you can be certain that all your setters are side-effect free if you re-assign the same value and that you never, ever, care about the overhead associated with double-setting values needlessly. “Yes” and “yes”? Cool. “Mmh” and “not sure”: Weep with me.

]]>
<![CDATA[SwiftSuspenders 1.6: A Tale of Small Changes and Big Plans]]> 2011-02-05T16:15:28+01:00 http://tillschneidereit.net//2011/02/05/swiftsuspenders-1-6-a-tale-of-small-changes-and-big-plans I just released version 1.6 of my not-so-small-anymore IoC container SwiftSuspenders. This release marks the end of the line for 1.x-releases, all future development work will go towards the all-new, shiny 2.0 release. Bug fixing will continue as per usual, of course.

Small Changes?

Yes – in 1.6:

  • An easy but nevertheless significant performance optimizations for child injectors: Through a slight refactoring of the InjectionPoint class, I was able to make it fully independent from the injector that creates them, enabling them to be shared among all injectors in the VM instance. This allows them to be cached once, removing the significant performance overhead associated in inspecting classes to find injection points for all but the first injector.

  • Some usability improvements such as better error, warning and info messages on trying to instantiate interfaces, re-mapping previously mapped types and construction of dummy instances to work around Flash Player bugs.

Right, but Big Plans?

Indeed – for 2.0!

For the next major release, I plan to change things up quite a bit. The main features on the roadmap are:

  • a much nicer API
  • factory mappings
  • field mappings
  • live injections
  • optional injections
  • weak mappings in child injectors
  • full live-cycle management with [PreDestroy] annotations
  • a new format for external, runtime-loadable definition of both injection points and type mappings
  • full implementation of the metadata standardization @darscan started, for example:
  • optionally shortening [Inject(name='name')] to [Inject('name')]

That sounds just swell, but I’d really like some details, please!

Of course you do!

The shiny new API

SwiftSuspenders’ API mainly consists of methods that facilitate the mapping of types (and, optionally, names) to responses. Internally, this already is a two-step process: First, an object is created that contains the request configuration (i.e., the type and the optional name) and second, this request is assigned a response of a certain type: A value, class, singleton or rule mapping.

While 2.0 will ship with a façade to make porting from 1.x easy, the real interface will expose this process as the two steps it really is. Look forward to seeing mapping commands that look (approximately) like this:

1
2
3
4
5
6
7
8
9
10
injector.map(YourClass); //current equivalent: injector.mapClass(YourClass, YourClass);
injector.map(YourClass, 'name'); //current equivalent: injector.mapClass(YourClass, YourClass, 'name');
injector.map(YourClass).to(YourClass); //equivalent to the first mapping (i.e.: optional)
injector.map(YourClass, 'name').to(YourClass); //equivalent to the second mapping (i.e.: optional)
injector.map(YourInterface).toType(YourClass); //current equivalent: injector.mapClass(YourInterface, YourClass);
injector.map(YourClass).asSingleton(); //current equivalent: injector.mapSingleton(YourClass);
injector.map(YourInterface).toType(YourClass).asSingleton(); //current equivalent: injector.mapSingletonOf(YourInterface, YourClass);
injector.map(YourInterface).toValue(value); //current equivalent: injector.mapValue(YourInterface, value);
injector.map(YourInterface).toRule(otherRule); //current equivalent: injector.mapRule(YourInterface, otherRule);
var request : InjectionRequest = injector.map(YourClass); //current equivalent: var request : InjectionConfig = injector.getMapping(YourClass);

Basically, the API will be somewhat more DSL-ish, without going all the way into that direction, though: I like to think of it as bundling up all parameters related to one concept in one method call: First everything related to what gets mapped, then, optionally, to what it gets mapped and finally, how its being mapped.

Additionally, the small rest of the API will be subject to some tweaks, I suppose.

Factory mappings

I haven’t really gotten through the concept phase for these. The absolute minimum is support for injector.map().toFactory() and injector.map().toFactoryMethod(), but if I come up with some clever mechanism for parameterizing specific injections, I would like to support that as well.

Field mappings

In order to turn SwiftSuspenders into a light-weight one-way binding solution, 2.0 will support mapping of fields in objects with injector.map().toField(fieldName, inObject). If the mapped field is bindable, SwiftSuspenders will listen to its change events and update the affected live injections:

Live injections

Now those are something I’m really looking forward to. By specifying the live-parameter in your Inject-metadata (as in [Inject(live)]), you basically create a one-way binding that updates the value as soon as the associated mapping changes or, in the case of field mappings, the relevant binding event is dispatched as described above.

Optional injections

These are exactly what you think they are. [Inject(optional)] will instruct the injector not to throw an exception if it can’t find a mapping for the requested type.

Weak mappings

Imagine you have a module that you want to test – or perhaps even deploy – standalone but also want to load into a bigger application. Now this module might have some configuration that’s different based on what context it gets loaded into. If its loaded into another application, all or parts of the configuration should be supplied by that application, but if its running standalone, it has to deal with configuration all by itself. Enter weak mappings: These instruct the injector to always ask its parent injector if it has a mapping for the injection request. Only if that returns empty, the weakly mapped value, in this case the module’s configuration, is used.

Tear-down with [PreDestroy]

Just as [Inject] is used to build object graphs, [PreDestroy] facilitates tearing them down. When instructed to destroy a certain instance that it created itself or that was injected into with injector.injectInto, SwiftSuspenders will first go through all injection points in the instance and destroy those recursively (if they are only used by this instance, not if they are singleton or value mappings, of course) and the invoke all methods marked with [PreDestroy] metadata.

This will probably be used to replace the currently hard-coded preRemove and onRemove methods in Robotlegs mediators.

New runtime-loadable configuration format for injection points and mappings

The current XML-based configuration format was solely meant to work around restrictions in the Flash CS* AS3 compiler which doesn’t support custom metadata out of the box. This problem has since been worked around, rendering the format obsolete as it is right now. As quite some people expressed interest in being able to mix hard-coded and runtime-loaded configuration, I will try to come up with a good format for that. For now, I don’t have anything in that direction, so we’ll see how that goes. And if you want to define just such a format: Please do (and tell me about it).

Standardization FTW

One thing I like about Robotlegs is how @darscan went to great lengths to prevent as much lock-in as possible: Not only is the framework’s core just a set of interfaces that makes it easy to roll your own for each part, the framework specifically tries to make as many parts of your application independent and even ignorant of its existence as possible. Toward that end, Shaun started a metadata standardization effort with the goal of getting as much agreement on the format of injection point- configuration metadata as possible between the various IoC containers out there.

And while I like to think of SwiftSuspenders (especially in its future 2.0-form) as being a pretty decent IoC container implementation, you should definitely check out SmartyPants, Swiz, Dawn, Spicelib and other IoC containers if only out of interest. I’d also like for you to tell me of you don’t like SwiftSuspenders or you think it’s missing some Very Important Feature, though. Anyway, to allow you to switch from or to SwiftSuspenders as painlessly as possible, I’ll implement as much of whatever everyone decides upon as possible in 2.0 and future releases.

That’s quite a lot of work you just described. You really think you can handle all of it for 2.0?

Yeah, I know: This sounds like (and is) a lot. I’ll pack all of this up in the form of a roadmap on the github wiki, prioritizing stuff and distributing it across beta releases. Depending on when it makes sense to do a new major release (which in turn depends on when we decide to release Robotlegs 2.0), I might let one or two of the described features slip into 2.*.

But, some of these features already exist in forks other people published on github and which I was very bad at keeping up with. It is my hope that I can integrate much of these other great people’s hard work instead of doing much myself.

]]>
<![CDATA[Dictionaries in AS3: A tale of awesomeness and restrictions]]> 2011-01-14T12:38:13+01:00 http://tillschneidereit.net//2011/01/14/dictionaries-in-as3-a-tale-of-awesomeness-and-restrictions Update: @stray_and_ruby kindly made me aware of the fact that it isn’t entirely obvious what this post is about. I’m talking about a fairly obscure, but really handy usage of the Dictionary class: Implementing weak references to objects.
@sunjammer recently posted about the Dictionary class in AS3. I agree with him: Dictionaries are awesome.

Unfortunately, they’re only nearly as great as he describes them because of one little snag: Weak Dictionaries are only “weakly keyed”, not “weakly valued”, meaning that assigning an object as a value creates a strong reference to that object – even if that very same object is also used as the key for the entry.

That’s especially unfortunate because it doesn’t allow for efficiently implementing weak references with low overhead:

Instead of using something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package
{
  import flash.utils.Dictionary;
  public class WeakReference
  {
    private static const _referencesHolder : Dictionary = new Dictionary(true);
    private static var _nextReferenceID : int = 0;
    private const _referenceID : int = _nextReferenceID++;
    public function WeakReference(target : *)
    {
      _referencesHolder[_referenceID] = target;
    }
    public function get target() : *
    {
      return _referencesHolder[_referenceID];
    }
  }
}

you have to use something with much more overhead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package
{
  import flash.utils.Dictionary;
  public class WeakReference
  {
    private const _referenceHolder : Dictionary = new Dictionary(true);
    public function WeakReference(target : *)
    {
      _referenceHolder[target] = true; //every basic type works as the value
    }
    public function get target() : *
    {
      for (var value : * in _referenceHolder) return value;
      return null;
    }
  }
}

On another note, I naturally had to google “awesomeness” and what do you think ensued? Correct: Awesomeness! Specifically, the result contained, besides lots of links to Barney Stinson and HIMYM in general, this fantastic service. I mean seriously: Who doesn’t like to be reminded of being awesome? And if you ask me, $45 a month is dirt cheap for that happening reliably and on a daily basis. (Just as the providers of the service, I’m only half-joking, btw. I’m sure there are lots of people out there whose life can be improved by such a service.)

]]>
<![CDATA[SwiftSuspenders 1.5, or: A tale of robots and refactorings]]> 2010-05-15T17:41:01+02:00 http://tillschneidereit.net//2010/05/15/swiftsuspenders-1-5-or-a-tale-of-robots-and-refactorings 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:

1
2
3
4
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:

1
2
3
4
5
6
7
8
//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 thigh here)

1
[Inject] public var knee : Knee;

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

1
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:

1
2
[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:

1
2
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:

1
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 injection 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.

]]>
<![CDATA[Announcing SwiftSuspenders 1.0]]> 2009-11-24T21:59:03+01:00 http://tillschneidereit.net//2009/11/24/announcing-swiftsuspenders-1-0 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.

]]>
<![CDATA[Improved reflection support in Flash Player 10.1?]]> 2009-11-22T01:23:14+01:00 http://tillschneidereit.net//2009/11/22/improved-reflection-support-in-flash-player-10-1 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:

1
2
3
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:

1
2
3
4
5
6
7
8
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:

1
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.

]]>
<![CDATA[Introducing SwiftSuspenders]]> 2009-09-21T16:20:43+02:00 http://tillschneidereit.net//2009/09/21/introducing-swiftsuspenders 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.

]]>
<![CDATA[On finding Unicode ranges]]> 2009-06-06T20:14:20+02:00 http://tillschneidereit.net//2009/06/06/on-finding-unicode-ranges 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.

]]>
<![CDATA[Introduction]]> 2009-06-06T18:39:04+02:00 http://tillschneidereit.net//2009/06/06/introduction 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.

Update: This is oh so very much outdated that you shouldn’t even read it. Really.

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.

]]>