Bend Over; This won't Hurt a Bit: ActionScript 3.0 Dependency Injection.

It's Time for Your Dependency Injection!
The go-to guy in dependency injection is Martin Fowler, but I first became aware of it in one of Miško Hevery’s posts, and it was the topic of his discussion at last year’s OOPSLA meetings in Orlando, Florida. In looking around for different takes on dependency injection (or DI as all the cool kids call it), one of the better ones was by Griffin Caprio on an MSDN page. Caprio uses a Factory example, but alas, it’s an Abstract Factory, and I get the heebie-jeebies just looking at the class diagram. So explaining DI using an Abstract Factory is like explaining simple arithmetic using quantum physics. (Just clench your teeth and click the link to get the rest.)
The Just-Right Explanation
I suppose it takes no small amount of cheek to claim one’s own explanation is the right one, but since that seems what everyone else is doing, I don’t want to rock the boat. (The exception is Wikipedia that doesn’t understand its own explanation and says so!) In part, the problem stems from the fact and a lot of dependency injection is handled by frameworks like Guice, PicoContainer and Spring. Then the discussion quickly turns either to a discussion of which framework to use (or even why to avoid one) and why dependency injection is (generally) a good thing. (Of course that discussion is carried out assuming that you fully understand what the framework is doing and all the 1,352 libraries in Java.)
According to Martin Fowler, who with others coined the term, Dependency Injection, we have three kinds of DI—all of which are a sub-type of inversion of control (IoC). They are:
- Type 1 IoC (interface injection)
- Type 2 IoC (setter injection)
- Type 3 IoC (constructor injection)
For this post, I’ll focus on only one type—Type 3, Constructor injection, and I’ll generate an example in ActionScript 3.0. Besides, I’m only going to focus on a single aspect of DI and try and keep things at a general enough level for everything to be kept in perspective. Further, I’ll not build a DI framework or recommend one. This post is one just to introduce the DI concept in the hopes of generating some discussion.
It All Starts with the Component and Service
Following Fowler’s lead, I’d like to begin with a request for a service from a component. Both the Component and Service are chunks of software (possibly classes) where one is dependent on the other for some kind of service. Fowler had a model in mind that reminded me of an ActionScript 3.0 application making a database request via PHP. In this case the PHP is the foreign application that provides the service to the AS3 component.
In the context of design patterns, we can easily imagine one class using another class for services it does not offer itself. Indeed, the whole idea of DI appears to be hard-wired in many of the patterns we’ve discussed. Further, the Hollywood Principle is an inversion of control concept and DI is a type of inversion of control; so much of what we’ll discuss is not new to those familiar with design patterns.
Why Dependency Injection? Martin Fowler wanted to explore an ongoing issue in programming—how to wire different components together. One common answer to the issue of connecting objects from different projects is Inversion of Control (IoC), and Dependency Injection (DI) represents a specific type of IoC. However, I also see it as the right step in reducing service class overhead as well. (Getting the mother-in-law with the spouse when all you want is just the spouse. )
What is Dependency Injecting? Generally, the discussions about DI include a review of the framework[s] that support a particular DI do, but dependency injection itself is about placing an object (service) needed by a component into the component. The component depends on the service for a certain functionality, and it is injected into the component. Type 3 IoC (constructor injection) is done by injecting the service into the component’s constructor. The following classes illustrate this using 1) a client class, 2) a component class, and 3) a service class.
The first step is to set up the Component class as “injectable” by providing the constructor class with a service parameter. This parameter is the service that the Component depends on. Then we’ll provide some operations (methods) that use the service in the Component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package { import flash.display.Sprite; public class Component extends Sprite { private var service:IService; public function Component(otherService:IService) { service=otherService; } public function doPlant():void { service.plant(); } public function doHarvest():void { service.harvest(); } } } |
Next, the service interface provides two methods. The methods were opposites but related, plant and harvest, and so they probably would not be needed at the same time. (This stems from reading too much Miško Hevery who cautions against unwittingly leaving a whole class to be instantiated when you only need some of its operations.) Anyway, the Service class simply implements the IService interface. Both the interface and class follow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //Interface package { public interface IService { function plant():void; function harvest():void; } } //Service package { public class Service implements IService { public function plant():void { trace("Plant the seeds or seedlings."); } public function harvest():void { trace("Mow and harvest the wheat."); } } } |
Given the arrangement of the Component class, it can now inject the Service into an instance of the Component. Here, we’ll use a simple Client to do so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package { import flash.display.Sprite; public class Client extends Sprite { private var otherService:IService=new Service(); private var useServiceThroughComponent:Component; public function Client() { //->otherService<- is dependency injected in following line useServiceThroughComponent=new Component(otherService); useServiceThroughComponent.doPlant(); //Or you can use the other functionality; //useServiceThroughComponent.doHarvest(); } } } |
The purpose of DI is to maintain loose coupling between the Component and Service. The service becomes the one injected into the component in the Client. Further, it is typed as the service interface, and so there’s minimal coupling with a concrete class (actual service). However, as you can see in the example, you have full use of the services. The Component has no idea of what’s involved in the details of the service it has requested because it is through the interface and any changes to the service would not affect either the component or service. Further, the dependencies are injected through a constructor parameter.
Is a DI Framework Necessary for AS3 Design Patterns?
I’d feel a lot more comfortable about DIs if I knew more about DI frameworks. I know of none that have been implemented in and for AS3, but this may be something worth considering when using AS3 with PHP or ASP.NET/C#. However, I suspect we’d be better served by having design patterns guide both AS3 designs and PHP designs and then see if PHP services (e.g., database work) could smoothly be integrated and loosely incorporated by AS3.
I’d need to look at DI frameworks far more closely before making up my mind, but inversion of control is already hard-wired in so many patterns, that I’m not at all sure that DIs would not be redundant. I could be wrong about that, but inversion of control (IoC) is built into many patterns already. However, I wouldn’t mind being proven wrong, and I welcome comments.
Related posts:

Bill Sanders
Hi William,
Most AS3 DI frameworks use the Meta data syntax to remove the overhead of traditional wiring. For some the wiring is purely XML driven which has its pros and cons. A few worth looking at are RobotLegs, Dawn, Swiz (Flex), Parsley. Knock yourself out!
Personally, I like to see my code as is with no meta data. Old skool I guess, but then again the cool kids never had packed lunches now did they?
Hi Wesley,
Thanks for the information. I’ll take a look at those. Know of any kind of specific uses they have for DI frameworks? Are they for connecting up with anything specific (e.g., a db language, a webservice) or are they general?
Any further information would be welcomed.
Thanks for the note,
Bill
Hi William,
It’s always a pleasure to read your articles.
Just in case you decide to give Robotlegs a try, here are some starter links:
http://www.robotlegs.org/
http://github.com/robotlegs/robotlegs-framework/wiki/best-practices
http://knowledge.robotlegs.org/discussions
A very short description of the framework:
“At its core, Robotlegs is a set of modular utilities and interfaces that provide tools to ease these communication tasks, reduce repetitive coding tasks, and manage dependency injection within your application. In addition to this core set of tools, Robotlegs provides a lightly prescriptive MVC+S (Model, View, Controller, and Service) implementation to get you started.”
from
http://insideria.com/2010/06/an-introduction-to-robotlegs-a.html by Joel Hooks
Ondina
Hi Ondina,
Thanks for the information. How exactly does this work in terms of promoting loose coupling? For all of this to make sense, (to me at least), I’m interested in where IoC hooks into a design pattern (not MVC) and how this is accomplished.
The links you sent are a great help, but I’d be interested why Robotlegs is the best solution.
Kindest regards,
Bill
Hi William,
I’m in trouble now!
I’m not very good at explaining, so let me see if I can get some help from the creator of the framework, Shaun Smith ( @darscan) or other contributors
Ondina
Hi Bill,
There are numerous strings to the robotlegs decoupling bow, but here are a few in the hope that you’ll dig a little further:
- The framework provides a shared eventDispatcher (by injection) so that models, services and mediators can communicate through that channel without knowledge of the communicator/recipient.
- The mediatorMap allows views to be automagically mediated, and remain totally agnostic of the application. When a mapped view hits the stage the appropriate mediator is created, and has access to the shared eventDispatcher to receive and send application events, translating to and from the view API.
- Injections can be mapped such that the dependency is specified as an interface, and is fulfilled with a concrete type. This can be a ‘singleton’ (small s) – the injector ensures there is a single instance filling these dependencies, but you’re free to create further instances outside of the injector.
- This creation of dependencies as interfaces rather than concrete types allows you to mock those interfaces for stubs/verifiers in your tests.
- A command map allows you to pair an event to a command. The command can be injected with the models/services it needs to act upon. The application logic is entirely captured in that command (which again can depend on interfaces and not concrete types).
- The only requirement of an Actor (a class that wants to play on the framework) is that they implement the ‘get/set eventDispatcher():IEventDispatcher’ interface.
No statics, no globals, singletons (with a small s), coding to interfaces, separation of views from application… all adds up to amazing decoupling, and very testable code.
The framework also encourages you to use the mediator/command map and refrain from injecting into views, or injecting views around. It’s possible but it’s harder than doing it the ‘right’ (decoupled) way.
In addition, the way the injections are performed – either on a public var or a public setter function – means that the code can be used elsewhere in conventional ways. You’re not bound to the framework either!
I’m sure Shaun or Joel will pop up and say more
Stray
Howdy Bill,
I’d like to point out that Robotlegs is not a DI framework/library, but rather a toolkit that assists/extends DI. By default Robotlegs uses a library called SwiftSuspenders, via an adapter, to perform the actual injections.
Here’s a list of some notable AS3 DI libraries:
Dawn (Guice style)
SmartyPants-IOC (Guice style)
Spicelib (used by Parsley)
Spring ActionScript (Spring style)
SwiftSuspenders (used by RL)
Swiz (Spring-ish)
All these libraries work in roughly the same way (the differences are mostly just configuration syntax):
You create a container (a factory), you provide it with rules, and you let it construct your instances. The container uses reflection (describeType) to determine dependencies and then resolves them recursively.
Here’s a document I put together that might help explain automated DI to a certain extent:
http://github.com/robotlegs/robotlegs-framework/wiki/Robotlegs-Internals
Automated DI is one of those things that seems quite magical at first, but is actually quite mechanical and straight-forward once the concept “clicks”.
Hi Stray/Shaun,
Thank you both. I’m going to spend some time with your document (the one Shaun put together.)
There seems to be a lively DI community, and it’s great to hear from you all. Right now I’m on my way to Reno, NV for the annual OOPSLA (now called SPLASH) conference, and I hope to chat up some of the folks there about DI.
I want to spend some time with DIY DI just to better understand the process independent of design patterns. Your comments and example has been terrific for a running start.
Kindest regards,
Bill
They are all about wiring objects as and when required and also the communication of these objects. The meta notation simply marks one of the three types of IoC ready for injection. These objects can be a service or a view for example.
Obviously there’s more to it than just wiring, each framework offers different advantages, like mediation of views etc. but the core concept remains IoC through DI.
Hi Wesley,
You mention “IoC” through “DI” — that is intriguing. I’d be interested in your take on IoC through something other than DI. (The Template Method design patterns comes immediately to mind.)
Also, how are these frameworks evaluated in terms of code re-use? This is a very interesting can of worms. Besides, some may want to have a go at DIY DI (die-die) and have some fun.
Thank you again for your insights,
Bill
Hey Bill,
Some other forms of IoC are:
Service Locator
Factory Pattern
PureMVC, for example, employs the Service Locator pattern:
collaborator = facade.retrieveProxy(“SomeKey”);
The problem with those patterns is that they are quite intrusive, and they limit code re-use, because your class needs to know “how” to get its dependencies, and it gets hard-wired to that mechanism. Also, your class is given an instance (the factory or locator) that it doesn’t actually need to do its job – it needs the collaborator, not the factory/locator.
DI, on the other hand, removes that unnecessary burden from the client class. All the client does is “declare” what it needs to do its job – the task of constructing/locating those dependencies is left to a more suitable entity: this can be done automatically (by a DI container) or manually (by a developer, perhaps inside a unit test).
Hi Shaun,
Thank you for you ideas and explanations. Most of the comparisons I’ve seen that compare DI with Service Locators come down on the side of DI. If PureMVC does as well, you can take that up with Chandima.
However, I’m not so sure that the Factory Method is as intrusive as you imply, especially compared with a framework involving XML files. Often there is a reference to the “factory method” as an operation and not a design pattern. The pattern includes a Creator and Product class, and the Client is isolated from both the instantiation of and configuration of the concrete production. Loose coupling is achieved by isolating the Client from the Product through the Factory (Creator class); so I’m not quite sure how you see the Factory (Method or Abstract) being intrusive.
Anyway, I’d like to see an example where the Factory is intrusive and the DI is not.
Kindest regards,
Bill
Hi Bill,
The Factory is intrusive because the client shouldn’t need to know about the factory in the first place. It doesn’t need the factory, it needs the product. Consider the DI approach:
It’s simple and straight-forward. The class has a dependency. It declares that dependency in its constructor. There is no intermediary. The class can easily be used in many contexts, including unit tests.
Now consider the same thing using a factory:
Now our client is coupled, unnecessarily, to another entity (the factory). It doesn’t actually use the factory directly. However, it’s not too bad as we are passing in a simple factory by interface. If the factory is simple, has few dependencies, and is provided along with the client, then it’s not too bad a situation. We could probably use the client in a variety of contexts without too much hassle.
Now consider this:
Now we’ve introduced another piece of coupling: we need to know how to pull things out of the factory – in this case, we need to know the magic string name of the service.
This gets much worse when the factory (or locator) belongs to a framework – our simple class gets statically coupled to that framework, and can not even be compiled without it.
If the factory/locator is built on the Singleton pattern we end up with a client class that is not only coupled to a particular version of a particular framework, but is also coupled to a particular time/state.
Factories still have their place of course. I’m just suggesting that DI is often the cleanest, simplest and most portable way to obtain references to collaborators.
It is my understanding that the use of the Template Pattern actually results in the Hollywood Principle or more accurately inversion of control. This is because the super or parent template method will call the sibling methods as and when required. The IoC described here is more of a family relationship, i.e. parent and child class methods.
I think IoC through a framework is a somewhat different relationship, i.e. strangers rather than family. I see DI in this use case as simply connecting these strangers through a central control point. In this relationship DI is certainly key for maintaining an IoC structure but not so much when using say the Template Design Pattern. This is not to say you can’t use DI and the Template Pattern together.
Because of the Hollywood principle, code re-use is high. None of the components or children need to know anything of the control system/framework to exist, they simply state what they need in order to do their thing and it’s up to the framework to provide. Because of this loose coupling, the component could very easily exist in another system/framework. This is possibly more true for components than say a View in a MVC style framework. Most Views require some contract or interface to interact with, and this makes them commutative within the realm of that framework only and most likely not in any other similar MVC framework.
Wesley,
Since I’m not a fan of MVC, primarily because it is not a specific solution to a certain kind of problem (other than loose coupling in general), it forces the developer to think in terms of dividing solutions into a Model – View – Controller and not a lot more. As a result,too many frameworks reflect an overly general solution to problems where other and better solutions exist. It’s not even in the GoF catalog. It’s an example of a valuable starting point that came to be used as the solution to loose coupling. (It akin to spending your life in the first grade and making improvements on first grade.)
So putting MVC aside, are DI frameworks something that will add value to or have value added to them by the GoF design patterns? Is the Iterator pattern enhanced by DI or does the Iterator enhance DI?
Kindest regards,
Bill
Hi Bill,
I like that and totally agree with your first grade example. I so often have scenarios where some developer works within one MVC framework and therefore can’t share their code with other developers who work in a different MVC framework. They aren’t commutable.
I haven’t tried it but DI should entirely be possible with the Iterator Pattern as it is simply another property with an interface type.
So one should be able to inject the collection provided the DI framework would support the wiring of a Collection. I guess that is the main question.
MVC is an application framework pattern, OR a component design pattern (a-la Smalltalk MVC).
It’s a way to introduce convention around solving what are suprisingly similar problems. I happily treat my MVC as both (smalltalk style and application framework). It’s a suprisingly easy prescription for developing conformal apps that other team members can understand quickly.
The benefit is simple to me, it means my team stops thinging about the code and starts thinking about the concepts. The concepts are a whole layer of code away from the nitty gritty implementation details. There are other ways of decoupling your concepts and details, no doubt, however each time I go looking for conceptual designs that fit, I don’t really feel like considering the best way to decouple that from the down-low (what services, how to model and display state and share information between actors in the system etc).
When i go to write a game, there’s a better conventional pattern (the game loop) for the bulk of the work so I don’t use MVC, when I go to write a traditional application, I use MVC. When I go to write a mobile application, I keep Model/View seperation in mind, but i use whats idiomatic (which on android seems to be ‘activities’ and ‘services’, which to me is MVC in another bit of clothing.
You might think of RL as a M-V seperation framework, It’s not traditionally “MVC” because the only real MVC IMHO is the smalltalk one. You can’t even “perfectly” achieve the smalltalk one with most modern UI frameworks.
Hey guys,
When I read about DI in actionscript and Spring Actionscript isn’t mentioned I need to chime in of course
Spring Actionscript is an actionscript implementation of Java Spring, amongst other things it offers configuration using XML, MXML and metadata.
http://www.springactionscript.org
cheers,
Roland
Hi Roland,
Thanks for sending in the link. I had no idea that an ActionScript version of Spring (or any other DI framework) was available.
Let me take a look at it. In the meantime, could you provide a little more (non-link) information about what exactly Spring does.
I’m asking all questions about DI frameworks out of ignorance, and I’m depending on you and others who have more experience with these frameworks to help fill in the gaps.
Kindest regards,
Bill
Your AS3 code seems to reflect a pure implementation of the “Strategy Pattern.” I guess Inversion of Control presents one more context of use for that design pattern.
Thanks for sharing.
Hi Didier,
The example of DI I used may almost be a Strategy pattern, but not quite. In the example I used I provided two methods, each representing an algorithm. The concrete Service has both plant and harvest methods, while a Strategy would have separated out the algorithms into two separate concrete classes.
Thanks for your comment and I hope to hear more.
Kindest regards,
Bill
Thanks for your insights, Bill!
Actually, from the GoF book, page 315, the Strategy Pattern’s intent is to define a *family* of algorithms. The Strategy (Compositor) declares an interface common to all supported algorithms, which is exactly what you did.
No big deal, as one can decide to separate the algorithms as the business dictates. But your implementation qualifies for a pure Strategy.
Thanks!
Is this Andreas?
You’re right, it is a family of algorithms and not just algorithms. Anyway, I’ve never been positive of what a “family” of algorithms are unless they mean algorithms that share the same interface.
Kindest regards,
Bill
Good point.
)
My understanding from the GoF book examples is that a family of algorithms is… what it means: a collection of algorithms for a strategy. Say you have a strategy about sorting. You can have an interface with the various sorting algorithms that may include, say, bubbleSort(…), linearSort(…), logSort(…). Each strategy has the same interface. A concrete strategy may implement them differently–and even re-use the implementation across strategies using the flyweight pattern.
A family of algorithm does not mean that every algorithm in the family has the same interface, as you seem to be unsure about.
Thanks!
–Didier
(I’m not Andreas, BTW
Hi Shaun,
Thanks for the example. You’re saying the DI through some kind of black box (for now at least) has fewer dependencies because the Client has no knowledge of it. However, with the Factory, even though the Client is simply using the Factory as a delivery boy to provide a Product has a greater dependency. I don’t know if I buy that any more than I’d buy a DI being a dependency because it is referenced by the Client. Further, you complicated it a bit by introducing a (possible) Singleton where there is no Singleton. (I suspect you just added that to scare me — and you did!)
Anyway, you have certainly got my interest in delving further into DI and RobotLegs in particular.
Kindest regards,
Bill
Hi Bill,
> “You’re saying the DI through some kind of black box (for now at least) has fewer dependencies because the Client has no knowledge of it.”
Yes. The client has a direct dependency on a collaborator and nothing else. But there is no black box, just a straight-forward dependency. How that dependency is supplied is of no concern to the client. The dependency could be provided manually, supplied though a factory, or injected automatically via a DI container.
If you are suggesting that a DI container is a black box, then it may be that the mechanic that drives such containers is unclear to you at this point – which is perfectly understandable, it does seem magical at first.
A DI container is really just a factory that recursively inspects and resolves dependencies by reflecting on type information.
> “However, with the Factory, even though the Client is simply using the Factory as a delivery boy to provide a Product has a greater dependency.”
Yes. The client now has two dependencies: the actual collaborator that it needs *and* the factory. Again, it doesn’t need the factory, it needs the collaborator. If the factory method signature has parameters the coupling is increased for each parameter.
> “I don’t know if I buy that any more than I’d buy a DI being a dependency because it is referenced by the Client.”
Anything that you reference becomes a dependency. Break the factory and you’ll break the client. Change the factory method signature and you’ll break the client. Delete the factory and you’ll break the client.
> “Further, you complicated it a bit by introducing a (possible) Singleton where there is no Singleton.”
At least one popular framework provides Service Locators built on Singletons, so it’s more common than you may think.
> “Anyway, you have certainly got my interest in delving further into DI and RobotLegs in particular.”
Awesome! But please bear in mind that Robotlegs is not a DI framework/library itself. To ease the learning curve you may want to explore SwiftSuspenders and/or Dawn on their own before delving into a DI automation framework like Robotlegs.
http://github.com/tschneidereit/SwiftSuspenders/blob/master/README.textile
http://github.com/sammyt/dawn/wiki/DawnInjections
Also, it’s worth bearing in mind that while Dependency Injection libraries are very, very handy for statically typed languages (like AS3 and Java), they are not as useful for dynamic languages (like Ruby) where dependencies can be swapped out at runtime.
Bestest Regards,
Shaun
Hi SqueeDee,
Thanks for joining this conversation. The SmallTalk version of MVC (or a Java, PHP or ActionScript 3.0) is just that–a version. The importance of design patterns is the relationship between classes and how that enhances re-usability; not the language you’re using.
Further, if you look at pages 5 and 293 in the Gang of Four’s book, you’ll see that the Observer is an alternative to the MVC resetting the participant relationships to Subject – Observer and ConcreteSubject and ConcreteObserver. Those collaborations make more sense to me than Model-View-Controller.
Kindest regards,
Bill
I wasn’t referring to “SmallTalk”, I was referring to “SmallTalk MVC” the version, as you put it.
MVC as a pattern, in the days of SmallTalk, was designed to seperate view and model at the component level.
It got bastardised into something that is not a class-oriented pattern, but an application architecture pattern.
I’m not arguing with your opinions re Smalltalk-Version MVC and observer, I’d have to give it more time than I have now to have any valuable input. I am however, pointing out that the “Architectural MVC”, which is not, in my opinion, a version of classical MVC, is a very valuable pattern in architecting applications. It’s been used to good effect in large scale applications.
Rails, Django, TG and a raft of other web frameworks are based loosely upon it (as best as something with long asynch cycles between view and controller can be based on MVC).
Robotlegs, Cairngorm, PureMVC, Spring.. a lot of application frameworks are based upon it.
It’s an architectural pattern, so looking at http://en.wikipedia.org/wiki/File:ModelViewControllerDiagram2.svg really leaves an over simplified perspective of what actually has a great many diagrams (per implementation), EG: http://github.com/robotlegs/robotlegs-assets/raw/master/diagrams/mvcs/robotlegs_schematics.graffle/QuickLook/Preview.pdf
or
http://darkstar.puremvc.org/content_header.html?url=http://puremvc.org/pages/docs/current/PureMVC_Conceptual_and_Intro.pdf&desc=PureMVC%20Docs:%20PureMVC%20Conceptual%20Diagram
At the Risk of getting TL;DR, now to reitterate my point, hopefully making it more succinct. Developers given a prescriptive and easy to learn methodology for keeping presentation logic out of the business rules of each tier of their application, are more likely to be able to:
1. Change the business rules with minimal impact
2. Understand the existing rules
3. Think at a level of abstraction using the problem domain language, not the programming language.
This I feel is the benefit of the MVC Architectural Pattern(s)
P.S. Why I like the Smalltalkian-MVC is because it fits well with the MVC architectural pattern, I can use the same framework for component design as I do for application design, always stepping up from the programming language into the problem domain language (or DSL).
Hi SqeeDee,
Thanks for the follow-up, and I appreciate your points. I’ll take a look at Fowler’s piece. My greatest concern with MVC is not that it’s inherently good or bad, but that it comes to be the only pattern developers ever look at and/or use. That’s why I see it as stuck in the first grade; just keep using the same pattern over and over, ad nauseam and never move on.
MVC sure beats procedural programming, though.
Kindest regards,
Bill
Also Martin Fowler discusses MVC in quite a few places, this is a great article: http://martinfowler.com/eaaDev/uiArchs.html
He talks pro’s and cons of observational patterns better than I can.
Hi Didier (Sorry about the Andreas),
I guess we ran out of replies here; so it’s down here for your latest comment. We read the same thing; there’s just more than one interpretation . Your example of the family of algorithms with sorts isn’t quite clear–to me at least. You say a Strategy can have different algorithms for sorting. (bubble, linear, etc.) You have a Strategy interface (IStrategy we’ll say). Are you saying that:
1) Each of the different algorithms implements IStrategy (That’s what I meant when I said they all have the same interface. They just implement it differently in a concrete class)
2) Each sort is a Strategy and the algorithms within the Strategy implement…What?
Anyway, I would not agree that the separate algorithms constitute a Strategy, but instead they are a strategy that implement the same interface (as GoF note on p. 315)–that is each is a concrete strategy. We may mean the same thing just saying it differently.
The issue about a “family of algorithms” is inherently vague because one is left to assume what a family is. It is a concept in this context without boundaries. Sort algorithms seem to both of us to constitute a family because we’re used to categorizing them that way. So when you say, “it’s just what it says it is”, that I can see; so let me put it this way, “Exactly, what do they mean by family?” I’ve used the Strategy pattern a good deal, but I’ve not specified family besides thinking that certain algorithms more or less seem to go together—like sorts. However, I’ve also used Strategy patterns with different SQL algorithms—one for search; another for writing data; another for changing data, etc. The “family” is the SQL “family.”
As you can see, it can be broad or narrow. I would like to hear your thoughts on this issue. It’s not something that is discussed in any kind of depth in the GoF book; otherwise, I would not find as vague as I do.
Kindest regards,
Bill
Hi Bill,
I think we agree.
To me GoF patterns are meant to be “loose” in the good sense of the way, because they solve recurring problems than can show in so many business contexts. They’re supposed to help us solve business problems–whatever business means–in a way that will adapt to business changes.
In the case of the Strategy, the analysis of the business dictates what a ‘family’ means. A given family of, say, SQL algos can make sense for a given business, but may not for another. Making “universal” strategies would be extremely tough. There’s always a balance of granularity and simplicity that is optimal for any class of projects. But in general, I tend not to multiply interfaces artificially, for “just in case.” I went too far in the past in that direction and got burned by it; it just lengthens development time unnecessarily, and after a while code more tedious to maintain and read. Now I tend to go simple with what the business dictates, and break down interfaces later if needed.
If strategy families naturally reflect the business at hand, they will likely evolve more smoothly with business changes. Their implementation can also be mere Adapters/Visitors to a pool of algorithms for which there are not necessarily interfaces (e.g. library you cannot change)
What matters to me at the pattern definition level, is the fact that every algorithm need not have the same method signature, because that’s not what the pattern is about. The signature is at the Strategy interface level.
That was the point of my previous comments, and I think we agree about that.
How to distribute algos across the semantics of the strategies is indeed not covered by the pattern–and should not, either.
Hope that makes sense,
–Didier
Hi Didier,
Looks like we agree and just expressed it differently. In any event, we got to discuss some of the finer points!
Kindest regards,
Bill
Laura Aurguello has a presentation from the 2009 MAX on Adobe TV which does a great job of describing what DI Frameworks do in a general way, though she is specifically describing Mate. Check out http://tv.adobe.com/watch/360flex-conference/mate-flex-framework-by-laura-arguello/, around minute 37 if you don’t have time to watch the whole presentation.
Hi Amy,
Wow, now that’s a find! We have RobotLegs and Mate for DI frameworks. Thank you.
Kindest regards,
Bill
Adobe consulting seems to quite like Parsley http://blogs.adobe.com/tomsugden/2009/08/applying_the_presentation_mode.html, and Swiz has been a hot topic at 360Flex conferences this year.
I actually found this post when doing research on a post of my own “A Pragmatic Look at Dependency Injection Frameworks” New InsideRIA Blog Post: A Pragmatic Look at Dependency Injection Frameworks http://insideria.com/2010/10/a-pragmatic-at-dependency-inje.html
Hi again Amy,
What gold mine have you been hiding in? This is great stuff! Thank you very much and I’m sure that the DI folks appreciate it as well.
Have you taken the 5-click survey? We have ties and we need a tie-breaker for our next saturation!
Kindest regards,
Bill
Hi Amy,
I hope everyone interested in DI reads these comments because your post on DI frameworks ought to stir up a lot of interest. I highly recommend that those so interested take a look at Amy’s article. The post date is Halloween!
Wonderful to hear from you.
Kindest regards,
Bill
Aw, . I’m actually just learning this stuff, with a lot of help from people like Shaun, Stray, Laura Arguello, and Joel Hooks.
Now that insiderria is gone, the new link to Amy’s blog post is:
http://www.developria.com/2010/10/a-pragmatic-at-dependency-inje.html
Hi William,
Thanks for the link. I’m glad to hear that Amy’s blog is alive and well. We need the DI folks!
Kindest regards,
Bill
Hi Bill.
Seeing you intensively claiming that you don’t like MVC because it is a blind alley for some devs could you explain your “better choice”? The observer pattern you mentioned is very often used in combination with the mvc “pattern” and has a different responsibility.
What makes me feel odd about mvc sometimes is that I do not need the controller part all the time but at the end of the day its just a good way to keep your code organized – if there is a sudden change in requirements I have the ready made controller, where i can stick all the business logic instead of littering the UI module.
But again, what is your way to build apps without MVC – and I’m talking about whole apps not just proof of pattern concept apps.
Hi Mark,
In response to a similar query, I said,
The MVC represents arrested development in my view, but that’s because I found so much value in and spent so much time working with the Design Patterns developed by GoF. The MVC should win a Nobel Prize for introducing the notion of separating classes (participants) into interrelated groupings to solve general programming problems. However, using the MVC for everything is like building a house with only a hammer. The hammer is great for pounding in nails, but not so great for everything else required for house building.
Let me say that the MVC-only approach is much easier. You only need one general pattern. If you’re selling shoes, it’s a lot easier to have only one style and size and shove everyone’s foot into that one size than spend time trying to find the right size and style for individual requirements.
As for where to put the business logic in the pattern, that depends on both the pattern and the nature of the problem being solved. One of the first patterns I created was a Video Player using a State Design Pattern. The business logic is in the pattern; not just one participant. Another way of putting it is that the “model” is in recognizing that the focal point in a video player rests in the changing states of play, pause, stop and the other states that a video player goes through. Asking “Where is the business logic?” in a non-MVC pattern is like my asking, “Where is the state machine in the MVC?”
Do this: Look at Lady Gaga’s shoes and ask yourself, how would those shoes look on me? That’s how I view MVC.
Kindest regards,
Bill