Constructor Injection vs Setter Injection

Constructor injection is theoretically superior:

Constructor Injection vs Setter Injection
Constructor vs Setter Injection – Constructor is Better
Setter injection versus constructor injection and the use of required

Before I built RobotLegs I was sold on constructor injection. My prototype, however, used SmartyPants-IOC which lacked constructor injection, so I bit my lip and used setter injection. In practice I found that often, especially with framework actors, it was incredibly convenient.

Effort

Unless you use a code generator, constructor injection requires roughly 3 times the effort (more code) and is roughly 3 times more prone to human error than this form of setter injection:

public class SomeMediator
{
  [Inject] public var someView:SomeView;
  [Inject] public var someProxy:SomeProxy;
  [Inject] public var someService:ISomeService;

  public function SomeMediator()
  {
  }
}

Constructor injection requires twice the number of declarations and an extra assignment step.

public class SomeMediator
{
  private var someView:SomeView;
  private var someProxy:SomeProxy;
  private var someService:ISomeService;

  public function SomeMediator( someView:SomeView, someProxy:SomeProxy, someService:ISomeService )
  {
    // Boilerplate...
    this.someView = someView;
    this.someProxy = someProxy;
    this.someService = someService;
  }
}

Forgetfulness

Let’s consider what Misko deems the biggest problem with setter injection: forgetting dependencies.

In the case of setter injection, and in the context of the application itself (running on the RobotLegs framework), if we forget to set up a dependency rule, we’ll get a runtime error when the DI framework tries to inject into the Mediator (which happens automatically). This would be exactly the same for Constructor injection. A draw.

If we are instantiating the Mediator manually (in a unit test for example), and we don’t manually inject into it with our DI framework, then setter injection is obviously weaker – we won’t get the DI RTE, we’ll just get a null-pointer exception at some point in our test. Constructor injection is much better here, but something Misko overlooks is that constructor injection is more prone to human error from the inside. We have at least three places where we can forget to properly take care of our dependencies:

  1. We might declare the dependency in our constructor argument list, but then forget to store the passed value inside our constructor.
  2. We might declare a property on the class itself but then forget to ask for it in the ctor argument list.
  3. We might even be so delirious as to incorrectly assign the values in our ctor by excluding “this.”.

None of those mistakes will cause a compile-time error. As with setter injection, we’ll just get a RTE at some point. Again, a draw.

When we consider what a Mediator is, and the fact that Mediators are amongst the biggest candidates for re-factoring (we might start with one Mediator for a complex nested view, for example, and then break it out into several finely grained Mediators later), setter injection becomes even more convenient. Constructor injection requires more effort when dependencies change: 3 places need editing, including the constructor’s method signature – necessitating external changes for any manually instantiated instances.

Inconsistent State

Another charge against setter injection is that it can be responsible for objects in inconsistent states: directly after construction, and before injection has occurred, the object is not quite ready for use (it’s dependencies are missing). But this isn’t much of a problem when your architectural framework handles that side of things automatically – it instantiates and injects things for you.

Hybrids In Progress, A Sliding Scale

I’d also like to touch on the mixing of injection styles. Some people see this as akin to mixing coding standards in a project – ugly. At the same time, setter injection must be used under certain conditions (circular dependencies for example), so even purists have to mix styles sometimes. I’ve chosen to roll with it, and use what makes the most sense for the case at hand. Looking at actors in the RobotLegs framework, I’m inclined towards:

  • Setter injection for Mediators
  • Setter injection for Commands
  • Constructor injection for Proxies
  • Constructor injection for Services
  • Constructor injection for non-framework entities

My reasoning is that:

  • Mediators and Commands generally have more dependencies and require refactoring more frequently
  • Proxies and Services should have very few dependencies
  • Non-framework entities are more likely to be created manually

If we look at setter vs ctor injection on a sliding scale, we have:

  • setter -> constructor
  • convenient -> safe

We can always migrate from setter to ctor injection as classes settle down and their refactoring likelihood decreases:

  • setter -> constructor
  • sketchy -> final

Mediators, by their very nature, are the sketchiest parts of an application: they are tightly coupled both to the application and the view. Commands are coupled to the application. There is very little need to make either of these actors “safe” or “final”, and for flexibility it is wise to leave them “convenient”.

Proxies and Services, however, should not be too coupled to the application. They should be the “safest” most “final” classes in the interests of loose coupling and portability. I would start with setter injection and migrate to constructor injection as those components mature.

Prompted By:

This comment, thanks!

Another Architectural Framework, But Why?

robotlegssketchsmall

The State Of The Game

There are some great Flash and Flex application frameworks out there right now. Mate, Swiz and PureMVC (update: and Parsley!) stand out. The authors of these frameworks realized that the Flash Platform is different enough to the JVM to warrant a fresh approach to application design.

Someone mentioned recently that for such a young language (referring to Action Script 3), it’s quite surprising how many frameworks have sprung up around it. I’m not surprised at all: rich internet application development is complicated.. and it’s a pretty recent field in the grand scheme of things. It brings new (and often subtle) twists to traditional web and desktop software development. Writing elegant, maintainable code is hard enough as it is, but doing so on a rapidly evolving, heavily interactive platform.. well, people are still working on the best way to approach that (unless I missed the big news – in which case you can stop reading right here).

Hence all the groovy new architectural frameworks popping up. They share some common goals:

  1. Help developers write good, clean, understandable, testable, maintainable code
  2. Help them write that code faster
  3. Provide an easy-to-use mechanism for application/context/module subsystem inter-communication
  4. Provide an easy-to-use mechanism for wiring distinct parts of the application together whilst keeping those parts loosely coupled

And they succeed. To various degrees. I think they’re all pretty cool.

scenery

A Poke In The Back With A Sharp Stick

So why build another one?

  1. For fun – it’s how I learn stuff
  2. Because I find the other frameworks critically flawed

What kind of “critical” flaws?

  1. Singletons (big “S”)
  2. Central/Static Event Dispatchers
  3. Using the Display List as an Application Event Bus
  4. Casting
  5. The Service/Model Locator Pattern
  6. The Presenter Pattern
  7. Injecting into View Components

And what’s wrong with those things?

They are bad ideas:

1. The Singleton – Bad Idea

The standard Singleton implementation (that static getInstance method) is severely flawed. Unless you are writing device drivers, there is almost no excuse to touch a Singleton with a sharp stick.

Singletons bring bags of hurt to frameworks and applications.. suddenly, trying to build a modular application becomes an overly complicated affair, and unit testing becomes a nightmare. Singletons are viruses – they infect every class they touch.

And Multitons? If Singletons are evil, Multitons are diabolically evil. What makes the Multiton pattern incredible is that it manages to chump the Singleton as the worst Design Pattern Of All Time – no easy feat, and certainly the work of an evil genius with a wicked sense of humour. Not only do we have all the problems of the classic Singleton, we throw a poorly designed Model Locator into the mix – to pull out these horrendous Singletons we now need to use String keys.

Contextual singletons (as made possible by Dependency Injection frameworks) are a much nicer solution, they don’t require any extra (fluffy, nonsense, ill placed) code on the target classes themselves, and they allow identical applications/modules to exist side-by-side in the Virtual Machine without fighting and mass confusion. Which leads me to..

2. Central/Static Event Dispatchers – Bad Idea

As convenient as it is to use, a Central Dispatcher is a really bad idea. Another Singleton effectively. Pop two apps into the same SWF and watch, with excitement and glee, all the cross-talk that occurs – both apps responding to each other’s events. Oh noes!

Architectural frameworks generally provide you with an application event bus/channel/dispatcher to “chat” on, but this should be localised to the application itself (or some other context). Which leads me to…

3. Using the Display List as an Application Event Bus – Bad Idea

I find this one fairly disturbing too: dispatching system/application events along the display list. No!

A View is just that: “A view”, not “The view”. And don’t get me started on those innocent looking Event Maps! No, let’s move along…

4. Casting – Bad Idea

Besides wasting space and annoying programmers, casting distributes knowledge throughout a system – casting requires that you look elsewhere in your codebase for the “real” type.

And it weakens our lovely compile-time type checking (albeit temporarily), sending us back in time to our unhappy days building complex applications in the Flash IDE. And it’s boring. And it often occurs because of..

5. The Service/Model Locator Pattern – Bad Idea

Classes should not be responsible for “fetching” their dependencies – this is a separate responsibility that belongs somewhere else entirely – they should only contain code for doing their job. When classes reach outside to fetch things from the application/context they sneakily hide their dependencies away from the outside world.

Unit testers will despise you (which is a serious problem if you are writing your own tests) because it becomes incredibly hard to figure out how much set up needs to be done to write even the smallest of tests. You have to look inside the class for any calls to the Service Locator to find your direct dependencies, and then you have to look inside each of those classes to find theirs and so on. No no, that’s just cruel.

6. The Presenter Pattern – Bad Idea

Ok, it’s going to be tricky to back this one up. But think about it this way: the Presenter pattern requires that you modify your View component (to add a reference to a Presenter). Not a biggie, but once you’ve done that you’ve started coupling your View component to your application/context – a slippery slope.

I think the Mediator pattern is a much better fit for Flash and it’s Display List, and even more-so when it comes to Flex (and other UI frameworks with complex component life cycles).

It is far easier and cleaner to “wrap” around view components and poke their APIs than to have to modify (extend) them to make space for their Presenter references. Leave those components alone, leave them to the component developers, you’re supposed to be writing an application. While we’re on the Presenter pattern, let’s take a look at something dirty one might do in an attempt to salvage it’s reputation..

7. Injecting into View Components – Bad Idea

Besides being incredibly slow and wasteful (especially for Flex UIComponents), injecting directly into a View component couples it to your application/context.

View components, with any hope for reuse, should be as self-contained as possible. They should expose an API and dispatch Events. They shouldn’t be dependent on the application they are in or the framework it happens to be using. Give ’em ViewModels (M-V-VM) if you must, but don’t go and couple those ViewModels to your application, and certainly don’t inject them.

ducksaysyuk1

Wrapping Up This Micro-Post

Well that’s just your opinion, dude

Yeh, but I’m pretty proud of my little 7 point list there (cos I’m an OOP noob, and this stuff gets me amped). Using Dependency Injection I was able to avoid all those nasty things when building my own PureMVC-like framework.

But that just shifts the problem somewhere else

Yes, somewhere more appropriate.

Besides some convenient implementations (in the mvcs package), and some marker interfaces (in the core package) RobotLegs essentially provides two things:

  1. A Command Factory – for binding Commands to Events, and
  2. A Mediator Factory – for handling automatic Mediator creation and registration

Everything else is handled by a Dependency Injection framework and an Event Dispatcher.

theendissmall

Note: If you’ve been through all this before, I apologise, it’s new to me.. I’m a little slow.

Beware: the current default implementation of RobotLegs makes use of annotated setter injection. This breaks encapsulation, is open to misuse, and runs the risk of leaving objects in partially initialised states, but it’s very convenient! You can swap out SmartyPants-IOC for a Dependency Injection framework that performs constructor injection if you really want to play it safe.

I’ll admit straight-up (albeit as a footnote) that I never really gave Cairngorm much of a chance – preliminary research led me to demos, documentation and diagrams that screamed poor design and foreshadowed immense struggle. I’m sure there is a way to build a well designed Cairngorm application, but it looks like it’d take an awful amount of effort.. and code. And it probably wouldn’t be very much fun.

UPDATE: Removed some words that made me sound like a douche bag.

Flash Mousewheel Scrolling on Mac OSX

Update: This was fixed and released in Player 10.0.42.34.. Woop! (Wed, 9 Dec, 2009)

Mousewheel scrolling is not properly supported by the Flash Player on Mac OSX. There is a bug in the Adobe bug tracker here:

http://bugs.adobe.com/jira/browse/FP-503

But I feel that it’s misleading, and dilutes the issue. Firstly, the title has the word Flex in it. Secondly, it’s complaining about mousewheel support in Safari on Windows XP! Perhaps that is why it currently only has 10 votes.

The actual issue is that the mousewheel doesn’t work in any version of the Flash Player on OSX. It’s just a side-effect that it affects Safari on Windows.

This is a HUGE issue – Flash is all about Rich GUI these days, and OSX users are still without proper mouse support! How could this be an issue with only 10 votes?

At some point, the Flash Player will HAVE to support the Trackpad (with vertical and horizontal scrolling) properly, or risk continuing to look like a piece of ancient technology that doesn’t properly integrate with modern operating systems. I don’t think that’s an exaggeration: OSX users are generally very critical of UI nuances, and this is a biggie!

In the meantime there are a number of workarounds:

  • Simple Solution for Mousewheel Events
  • AS3 Mousewheel on Mac OSX
  • Mac OS X Mouse Wheel Support for ActionScript 3 Flash Applications
  • Flash MouseWheel Implementations for Mac OS X

Update: The bug entry has been edited a little to better reflect the problem.
Update: This was fixed and released in Player 10.0.42.34.. Woop! (Wed, 9 Dec, 2009)

Getting Started with FlashDevelop3 and AS3

Aha! Finally. Time for my first tutorial: Getting up and running with FlashDevelop3.

Firstly, FlashDevelop 3 only runs on Windows XP/Vista, and requires the .NET 2 runtime. Additionally, to compile AS3 code you will need the Java 1.6 runtime and the Adobe Flex SDK. Ok, let’s go!

Part 1 – Downloading, Installing, and Compiling a SWF

Let’s begin by setting things up and compiling our first SWF.

  1. Download the Adobe Flex SDK (just the Flex 3 SDK, not Flex Builder), and unpack it somewhere easy to find (C:FlexSDKFlex3).
  2. Download the latest version of FlashDevelop, install it and run it.
  3. Create a New Project, under ActionScript 3 choose Default Project, and give it a name (“hello”).
  4. In the Project Panel expand the “src” folder and open up “Main.as”
  5. In the constructor add the code: trace(“hello world!”);
  6. Hit Ctrl-Enter (or F5). A dialog should pop up asking if you’d like to open the AS3 context settings. Click “OK”.
  7. In the “Flex SDK Location” input field enter the path from step 1 (or browse to it).
  8. Hit Ctrl-Enter again. This should compile your code into a SWF and launch it in a tab. The Flex 3 compiler does incremental compiling, so the first compile might take a while, but subsequent compiles should be much faster.
  9. Make a “whooping” noise! “hello world!” should be displayed in the Output panel. You’ll find the SWF sitting in the “bin” folder. Notice that the project panel let’s you look into the guts of your SWF.. pretty damn sweet!

Part 2 – Some Adjustments

By default, FlashDevelop launches SWFs in it’s own version of the Flash Player. At the time of this writing, the player doesn’t perform quite as well as the official debug version of the Adobe Flash Player (besides, we want all the goodness of the very latest Flash Player!). Also, I find the tabbed view weird. So let’s change our setup a bit.

  1. Head on over to Adobe downloads, “Download the Windows Flash Player 9 Projector content debugger” and put it somewhere easy to find (C:FlexSDKFlashPlayer)
  2. Back in FlashDevelop, go to the main menu, click “Tools” and select “Program Settings” (or hit F10)
  3. In the left panel, under “Plugins” select FlashViewer, and point the “External Play Path” to the debug player executable from step 1.
  4. While you’re there, change the “Movie Display Style” to “External”. Click “Close”.
  5. At the top of the Project Panel click the “Project Properties” button (third from the left).
  6. Under “Test Movie” change the selection to “Play in external player”, and click “OK”.
  7. Hit Ctrl-Enter. Make the universal “Whazzamm” sound!

Part 3 – Attaching Assets to the Stage

Perhaps “hello world!” is not that thrilling for you. Fine.

  1. Create a folder called “lib” inside your project folder (alongside “bin” and “src”).
  2. Fire up Adobe Flash CS3 and create a new Flash File (Action Script 3.0).
  3. Save it inside the “lib” folder from step 1 and call it “assets.fla”.
  4. In the Flash IDE grab the Oval tool and draw a circle.
  5. Select the circle and convert it to a symbol by hitting F8 (or right-click and select “Convert to Symbol…”).
  6. Give it the name “Circle” and expand the Linkage panel by clicking “Advanced”.
  7. Under “Linkage” tick “Export for ActionScript” and click “OK”.
  8. Open up your Publish Settings (Ctrl-Shift-F12), deselect “HTML”, and flip to the “Flash” tab
  9. Tick “Export SWC”, click “Publish” and click “OK”.
  10. Save the file and close the Flash IDE.
  11. Flip back to FlashDevelop, and expand the “lib” folder in the Project Panel.
  12. Right-click “assets.swc” and select “Add To Library”.
  13. Replace our “trace” statement with the following code:
    var circle:Circle = new Circle();
    addChild( circle );
  14. Hit Ctrl-Enter. Loudly exclaim “Golly, this is the biznis!”.

Part 4 – Extending Assets, Adding Interactivity

Perhaps a plain old circle on the stage doesn’t really do it for you. You want some motion. You want some interactivity. Some filters. Fine then. Let’s do it..

  1. In the Project Panel, right click the “src” folder, select “New” “Class”, name it “ReactiveCircle” and click “OK”.
  2. Head to the end of the line “public class ReactiveCircle”, type “extends”, hit Space and select “Circle”.
  3. In the constructor type “filters = [new DropShadowFilter()];”
  4. On the next line type “addEventListener(” and press Ctrl-Alt-Space (this enables autocompletion for all available classes, not just the imported ones). Start typing “MouseEvent” but hit Enter as soon as you see it selected. Complete the statement with “.CLICK, onClick);”
  5. Move your cursor back onto the word “onClick”, press Ctrl-Shift-1 and hit Enter.
  6. Inside the generated event handler add the code: x += 10;
  7. Flip back to the Main class and change:
    var circle:Circle = new Circle();
    to
    var circle:ReactiveCircle = new ReactiveCircle();
  8. Hit Ctrl-Enter. Click the circle. Shout “Kapoww!”

Ok, it’s not a fully fledged RIA, but it should be enough to get you started.

Happy Flashing!