Skip navigation
Help

Dependency Injection

warning: Creating default object from empty value in /var/www/vhosts/sayforward.com/subdomains/recorder/httpdocs/modules/taxonomy/taxonomy.pages.inc on line 33.
Original author: 
Lars Kappert

  

We are talking and reading a lot about responsive Web design (RWD) these days, but very little attention is given to Web applications. Admittedly, RWD still has to be ironed out. But many of us believe it to be a strong concept, and it is here to stay. So, why don’t we extend this topic to HTML5-powered applications? Because responsive Web applications (RWAs) are both a huge opportunity and a big challenge, I wanted to dive in.

Building a RWA is more feasible than you might think. In this article, we will explore ideas and solutions. In the first part, we will set up some important concepts. We will build on these in the second part to actually develop a RWA, and then explore how scalable and portable this approach is.

Part 1: Becoming Responsible

Some Lessons Learned

It’s not easy to admit, but recently it has become more and more apparent that we don’t know many things about users of our websites. Varying screen sizes, device features and input mechanisms are pretty much RWD’s reasons for existence.

From the lessons we’ve learned so far, we mustn’t assume too much. For instance, a small screen is not necessarily a touch device. A mobile device could be over 1280 pixels wide. And a desktop could have a slow connection. We just don’t know. And that’s fine. This means we can focus on these things separately without making assumptions: that’s what responsiveness is all about.

Progressive Enhancement

The “JavaScript-enabled” debate is so ’90s. We need to optimize for accessibility and indexability (i.e. SEO) anyway. Claiming that JavaScript is required for Web apps and, thus, that there is no real need to pre-render HTML is fair (because SEO is usually not or less important for apps). But because we are going responsive, we will inherently pay a lot attention to mobile and, thus, to performance as well. This is why we are betting heavily on progressive enhancement.

Responsive Web Design

RWD has mostly to do with not knowing the screen’s width. We have multiple tools to work with, such as media queries, relative units and responsive images. No matter how wonderful RWD is conceptually, some technical issues still need to be solved.

start-image_mini
Not many big websites have gone truly responsive since The Boston Globe. (Image credits: Antoine Lefeuvre)

Client-Side Solutions

In the end, RWD is mostly about client-side solutions. Assuming that the server basically sends the same initial document and resources (images, CSS and JavaScript) to every device, any responsive measures will be taken on the client, such as:

  • applying specific styles through media queries;
  • using (i.e. polyfilling) <picture> or @srcset to get responsive images;
  • loading additional content.

Some of the issues surrounding RWD today are the following:

  • Responsive images haven’t been standardized.
  • Devices still load the CSS behind media queries that they never use.
  • We lack (browser-supported) responsive layout systems (think flexbox, grid, regions, template).
  • We lack element queries.

Server-Side Solutions: Responsive Content

Imagine that these challenges (such as images not being responsive and CSS loading unnecessarily) were solved on all devices and in all browsers, and that we didn’t have to resort to hacks or polyfills in the client. This would transfer some of the load from the client to the server (for instance, the CMS would have more control over responsive images).

But we would still face the issue of responsive content. Although many believe that the constraints of mobile help us to focus, to write better content and to build better designs, sometimes it’s simply not enough. This is where server-side solutions such as RESS and HTTP Client Hints come in. Basically, by knowing the device’s constraints and features up front, we can serve a different and optimized template to it.

Assuming we want to COPE, DRY and KISS and stuff, I think it comes down to where you want to draw the line here: the more important that performance and content tailored to each device is, the more necessary server-side assistance becomes. But we also have to bet on user-agent detection and on content negation. I’d say that this is a big threshold, but your mileage may vary. In any case, I can see content-focused websites getting there sooner than Web apps.

Having said that, I am focusing on RWAs in this article without resorting to server-side solutions.

Responsive Behavior

RWD is clearly about layout and design, but we will also have to focus on responsive behavior. It is what makes applications different from websites. Fluid grids and responsive images are great, but once we start talking about Web applications, we also have to be responsive in loading modules according to screen size or device capability (i.e. pretty much media queries for JavaScript).

For instance, an application might require GPS to be usable. Or it might contain a large interactive table that just doesn’t cut it on a small screen. And we simply can’t set display: none on all of these things, nor can we build everything twice.

We clearly need more.

Part 2: Building RWAs

To quickly recap, our fundamental concepts are:

  • progressive enhancement,
  • responsive design,
  • responsive behavior.

Fully armed, we will now look into a way to build responsive, context-aware applications. We’ll do this by declaratively specifying modules, conditions for loading modules, and extended modules or variants, based on feature detection and media queries. Then, we’ll dig deeper into the mechanics of dependency injection to see how all of this can be implemented.

Declarative Module Injection

We’ll start off by applying the concepts of progressive enhancement and mobile first, and create a common set of HTML, CSS and JavaScript for all devices. Later, we’ll progressively enhance the application based on content, screen size, device features, etc. The foundation is always plain HTML. Consider this fragment:


<div data-module="myModule">
    <p>Pre-rendered content</p>
</div>

Let’s assume we have some logic to query the data-module attribute in our document, to load up the referenced application module (myModule) and then to attach it to that element. Basically, we would be adding behavior that targets a particular fragment in the document.

This is our first step in making a Web application responsive: progressive module injection. Also, note that we could easily attach multiple modules to a single page in this way.

Conditional Module Injection

Sometimes we want to load a module only if a certain condition is met — for instance, when the device has a particular feature, such as touch or GPS:


<div data-module="find/my/dog" data-condition="gps">
    <p>Pre-rendered fallback content if GPS is unavailable.</p>
</div>

This will load the find/my/dog module only if the geolocation API is available.

Note: For the smallest footprint possible, we’ll simply use our own feature detection for now. (Really, we’re just checking for 'geolocation' in navigator.) Later, we might need more robust detection and so delegate this task to a tool such as Modernizr or Has.js (and possibly PhoneGap in hybrid mode).

Extended Module Injection

What if we want to load variants of a module based on media queries? Take this syntax:


<div data-module="myModule" data-variant="large">
    <p>Pre-rendered content</p>
</div>

This will load myModule on small screens and myModule/large on large screens.

For brevity, this single attribute contains the condition and the location of the variant (by convention). Programmatically, you could go mobile first and have the latter extend from the former (or separated modules, or even the other way around). This can be decided case by case.

Media Queries

Of course, we couldn’t call this responsive if it wasn’t actually driven by media queries. Consider this CSS:


@media all and (min-width: 45em) {
	body:after {
		content: 'large';
		display: none;
	}
}

Then, from JavaScript this value can be read:


var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');

And this is why we can decide to load the myModule/large module from the last example if size === "large", and load myModule otherwise. Being able to conditionally not load a module at all is useful, too:


<div data-module="myModule" data-condition="!small">
    <p>Pre-rendered content</p>
</div>

There might be cases for media queries inside module declarations:


<div data-module="myModule" data-matchMedia="min-width: 800px">
    <p>Pre-rendered content</p>
</div>

Here we can use the window.matchMedia() API (a polyfill is available). I normally wouldn’t recommend doing this because it’s not very maintainable. Following breakpoints as set in CSS seems logical (because page layout probably dictates which modules to show or hide anyway). But obviously it depends on the situation. Targeted element queries may also prove useful:


<div data-module="myModule" data-matchMediaElement="(min-width: 600px)"></div>

Please note that the names of the attributes used here represent only an example, a basic implementation. They’re supposed to clarify the idea. In a real-world scenario, it might be wise to, for example, namespace the attributes, to allow for multiple modules and/or conditions, and so on.

Device Orientation

Take special care with device orientation. We don’t want to load a different module when the device is rotated. So, the module itself should be responsive, and the page’s layout might need to accommodate for this.

Connecting The Dots

The concept of responsive behavior allows for a great deal of flexibility in how applications are designed and built. We will now look into where those “modules” come in, how they relate to application structure, and how this module injection might actually work.

Applications and Modules

We can think of a client-side application as a group of application modules that are built with low-level modules. As an example, we might have User and Message models and a MessageDetail view to compose an Inbox application module, which is part of an entire email client application. The details of implementation, such as the module format to be used (for example, AMD, CommonJS or the “revealing module” pattern), are not important here. Also, defining things this way doesn’t mean we can’t have a bunch of mini-apps on a single page. On the other hand, I have found this approach to scale well to applications of any size.

A Common Scenario

An approach I see a lot is to put something like <div id="container"> in the HTML, and then load a bunch of JavaScript that uses that element as a hook to append layouts or views. For a single application on a single page, this works fine, but in my experience it doesn’t scale well:

  • Application modules are not very reusable because they rely on a particular element to be present.
  • When multiple applications or application modules are to be instantiated on a single page, they all need their own particular element, further increasing complexity.

To solve these issues, instead of letting application modules control themselves, what about making them more reusable by providing the element they should attach to? Additionally, we don’t need to know which modules must be loaded up front; we will do that dynamically. Let’s see how things come together using powerful patterns such as Dependency Injection (DI) and Inversion of Control (IOC).

Dependency Injection

You might have wondered how myModule actually gets loaded and instantiated.

Loading the dependency is pretty easy. For instance, take the string from the data-module attribute (myModule), and have a module loader fetch the myModule.js script.

Let’s assume we are using AMD or CommonJS (either of which I highly recommended) and that the module exports something (say, its public API). Let’s also assume that this is some kind of constructor that can be instantiated. We don’t know how to instantiate it because we don’t know exactly what it is up front. Should we instantiate it using new? What arguments should be passed? Is it a native JavaScript constructor function or a Backbone view or something completely different? Can we make sure the module attaches itself to the DOM element that we provide it with?

We have a couple of possible approaches here. A simple one is to always expect the same exported value — such as a Backbone view. It’s simple but might be enough. It would come down to this (using AMD and a Backbone view):


var moduleNode = document.querySelector('[data-module]'),
    moduleName = node.getAttribute('data-module');

require([moduleName], function(MyBackBoneView) {
    new MyBackBoneView({
        el: moduleNode
    });
})

That’s the gist of it. It works fine, but there are even better ways to apply this pattern of dependency injection.

IOC Containers

Let’s take a library such as the excellent wire.js library by cujoJS. An important concept in wire.js is “wire specs,” which essentially are IOC containers. It performs the actual instantiation of the application modules based on a declarative specification. Going this route, the data-module should reference a wire spec (instead of a module) that describes what module to load and how to instantiate it, allowing for practically any type of module. Now, all we need to do is pass the reference to the spec and the viewNode to wire.js. We can simply define this:


wire([specName, { viewNode: moduleNode }]);

Much better. We let wire.js do all of the hard work. Besides, wire has a ton of other features.

In summary, we can say that our declarative composition in HTML (<div data-module="">) is parsed by the composer, and consults the advisor about whether the module should be loaded (data-condition) and which module to load (data-module or data-variant), so that the dependency injector (DI, wire.js) can load and apply the correct spec and application module:

Declarative Composition

Detections for screen size and device features that are used to build responsive applications are sometimes implemented deep inside application logic. This responsibility should be laid elsewhere, decoupled more from the particular applications. We are already doing our (responsive) layout composition with HTML and CSS, so responsive applications fit in naturally. You could think of the HTML as an IOC container to compose applications.

You might not like to put (even) more information in the HTML. And honestly, I don’t like it at all. But it’s the price to pay for optimized performance when scaling up. Otherwise, we would have to make another request to find out whether and which module to load, which defeats the purpose.

Wrapping Up

I think the combination of declarative application composition, responsive module loading and module extension opens up a boatload of options. It gives you a lot of freedom to implement application modules the way you want, while supporting a high level of performance, maintainability and software design.

Performance and Build

Sometimes RWD actually decreases the performance of a website when implemented superficially (such as by simply adding some media queries or extra JavaScript). But for RWA, performance is actually what drives the responsive injection of modules or variants of modules. In the spirit of mobile first, load only what is required (and enhance from there).

Looking at the build process to minify and optimize applications, we can see that the challenge lies in finding the right approach to optimize either for a single application or for reusable application modules across multiple pages or contexts. In the former case, concatenating all resources into a single JavaScript file is probably best. In the latter case, concatenating resources into a separate shared core file and then packaging application modules into separate files is a sound approach.

A Scalable Approach

Responsive behavior and complete RWAs are powerful in a lot of scenarios, and they can be implemented using various patterns. We have only scratched the surface. But technically and conceptually, the approach is highly scalable. Let’s look at some example scenarios and patterns:

  • Sprinkle bits of behavior onto static content websites.
  • Serve widgets in a portal-like environment (think a dashboard, iGoogle or Netvibes). Load a single widget on a small screen, and enable more as screen resolution allows.
  • Compose context-aware applications in HTML using reusable and responsive application modules.

In general, the point is to maximize portability and reach by building on proven concepts to run applications on multiple platforms and environments.

Future-Proof and Portable

Some of the major advantages of building applications in HTML5 is that they’re future-proof and portable. Write HTML5 today and your efforts won’t be obsolete tomorrow. The list of platforms and environments where HTML5-powered applications run keeps growing rapidly:

  • As regular Web applications in browsers;
  • As hybrid applications on mobile platforms, powered by Apache Cordova (see note below):
    • iOS,
    • Android,
    • Windows Phone,
    • BlackBerry;
  • As Open Web Apps (OWA), currently only in Firefox OS;
  • As desktop applications (such as those packaged by the Sencha Desktop Packager):
    • Windows,
    • OS X,
    • Linux.

Note: Tools such as Adobe PhoneGap Build, IBM Worklight and Telerik’s Icenium all use Apache Cordova APIs to access native device functionality.

Demo

You might want to dive into some code or see things in action. That’s why I created a responsive Web apps repository on GitHub, which also serves as a working demo.

Conclusion

Honestly, not many big websites (let alone true Web applications) have gone truly responsive since The Boston Globe. However, looking at deciding factors such as cost, distribution, reach, portability and auto-updating, RWAs are both a huge opportunity and a big challenge. It’s only a matter of time before they become much more mainstream.

We are still looking for ways to get there, and we’ve covered just one approach to building RWAs here. In any case, declarative composition for responsive applications is quite powerful and could serve as a solid starting point.

(al) (ea)

© Lars Kappert for Smashing Magazine, 2013.

0
Your rating: None

Why Robotlegs for Games?

The following covers why you would utilize the Robotlegs MVC architecture in a lightweight, Lua game for Corona. I’ll discuss the refactoring reasoning, the common problems you run across in game architecture, and their solutions with their pro’s and con’s discussed. Finally, I conclude on how Robotlegs helps solve these common issues, specifically in a Lua & Corona context.

I’ve started the port of Robotlegs to Lua to work in Corona if you’re interested in learning more.

Refactor First

In learning Lua & Corona, I quickly ran into 2 problems with the game I’m working on. The main code controller became way too large to manage. It wasn’t quite a God object (yes, the anti-pattern) because a lot of the View’s themselves handled some of the necessary messaging & logic. Regardless, time to refactor.

The first thing was to start using classes. Lua doesn’t have classes. There are a bunch of resources out there that explain how to do them in various incarnations. I went with a version that Darren Osadchuk, creator of the Corona bundle for TextMate.

The second thing was to start using packages. Lua doesn’t have packages. There are various ways of implementing them which are all confusing as hell. The easiest way is to just put your code in a folder and use that path in the require function, but you can’t utilize folders for Android in the latest build of Corona at the time of this writing.

These are the low hanging fruit of re-factoring, and has made a huge difference in code readability & maintainability.

Burdens of Encapsulation

The downside of OOP is that it’s encapsulated. While making something a black box with internally managed state & implied reusability is good on the surface, it pushes the burden of managing communication between those encapsulated objects to someone ones.

You have 3 options: globals, messaging dependencies, or mediation.

Global Variables: The Good

Most people agree global variables are bad… in larger software development. In smaller scoped software gaming, not so much. Let’s explore their benefits.

In a lot of languages, globals are part of the language design, irrespective of how the runtime and tools/IDE’s handle them. Some languages make them first class citizens with mechanisms and rules around how they’re often used. This makes them formalized, accepted, AND useful. This is important to understand.

If it’s formalized, it means the language designers deem their usage acceptable, AND expected.

If it’s accepted, it means others will use them, incorporate them into their projects, libraries, and training & writing materials. This also means it’s then promoted amongst the community, solutions and coding strategies/solutions are built around it. This doesn’t make it inherently “good”, just accepted in that particular community.

If it’s useful, the majority of people will use it if their job is using that language as opposed to hobbyists, or those who continue to explore the language and try different ways to solve similar problems with it off of their employer’s clock.

In Lua, globals are all 3. Formalized via _G, very similar to ActionScript 1′s _global, accepted in that people do in fact use them (unknowingly a lot I’d wager), and useful since the syntax to utilize globals is terse; a Lua hallmark. Notice both have the preceding underscore to ensure they don’t interfere with the developer’s potential to create a variable called G or global. While ActionScript 1 has some security implementations to prevent certain loaded SWF’s from writing/modifying existing definitions, they had the same mechinism with strorage, first via _level’s on a per SWF basis, and later a formalized _global. Lua takes it a step farther with a series of facilities to change “which” globals your using, etc. It’s also used in package naming strategies, OOP, etc.

As a globally accessible table, access to _G is fast. Fast is good in game development. You want to be part of the solution, not part of the problem.

Global Variables: The Bad

This differs from traditional software development. If you come from any formal software development, globals are considered extremely bad practice. There is a common strategy to use the Singleton design pattern to “get away with it”. Even those are considered bad practice when over used. In fact, Singletons are often created merely because the language doesn’t offer a formalized way of doing global variables (like ActionScript 3 vs. ActionScript 1).

Why? The 3 main reasons are application state coupling, access control, and preventing testability.

Application State Coupling

Application State Coupling refers to the state of your application being dependent on usually a series of global variables. I won’t get into the why’s, but MVC and it’s MVP derivatives (Passive View, Supervising Controller, Presentation Model) have solved most of the state problems. They keep visual state in the View’s (or anything that’s a GUI that you can see), and application logic & state in the Model layer somewhere. Your application is no longer coupled to a single variable being a specific value for your application to run, to exhibit a certain bug, etc. Each piece can (usually, hehe) be run independently, and if there is a problem, you know where to look, or at least where NOT to look.

An example is if your player is dying too quickly, you know the problem isn’t in the player code, or the controller code, but rather somewhere in the model where his life state is being access/set/updated. If you used a global, it’d probably be set in player itself, or perhaps by an enemy bullet that hit him, etc. No clue where to look.

Another side effect is adding new global variables. This leads to certain parts of your application expecting the globals to be a certain value at certain times. If they aren’t, things don’t work. Because they are many different places, it becomes extremely time consuming for you to debug and track down because you don’t necessarily know who is expecting what to be set to what, and why. This is more caused by access control, however…

Access Control

Access Control refers to who can access your data, and how. In Flash & Flex apps that are smaller, we’ll usually use the server as access control. Meaning, while we provide a GUI to allow people to create, edit, and delete users from a database for example, the actual PHP/Ruby/Python/Java on the server is the access control. No matter what we do in the Flex/Flash, we can be assured the server (usually… *sigh*) will ensure we don’t delete people we’re not allowed to, delete users en-masse, put illegal characters into their name, etc. Basically anything that would corrupt the data and screw the up the GUI.

In Flex/Flash apps, and nowadays in larger JavaScript web applications, you have a notion of “application logic” or “application state”. This is because this state is no longer on the server. It used to be with some web applications, usually in the session. When you go add something to your cart on Amazon.com, it’s not stored on the page that much beyond to show you a slight graphical change. Once you change pages, that JavaScript & HTML page state is now gone and replaced with a new one… but it remembers what you added. It does this because the state is saved on the server since the client needs to be stateless if the user refreshes the page to go to another one.

We don’t have that problem as much in Flash/Flex apps. We don’t go to pages insomuch as new “Views”. These views, or graphical representations of a GUI that have internal state, are still in the same SWF embedded in the same page in a browser that doesn’t go anywhere (same thing for an AIR app on the desktop or on a mobile device). Therefore, someone has to be responsible for holding the data in a variable or series of variables, and updating it when the server gives you new data.

These are usually classes called “Models”, and they’ll usually mirror their server-side equivalents in terms of CRUD operations: create, read, update, and delete. Where they differ is how much of the server-side provided data is parsed, error handling, data access control, and how that server-side data is set internally.

Suffice to say, good Model classes are encapsulated, ensure application logic is accessed by a public API that ensures security, doesn’t allow the internal data to be corrupted, and does all this within reason. An example is our Player’s health. If every enemy collision and bullet out there has access to the player’s health, we have no easy way to track down who may be potentially doing the math wrong on calculating the new hit-points and setting them to invalid values, or thinking the player is dead when she’s not, etc. If you have a PlayerModel, you can ensure your problem’s regarding hit-points and letting the world know about player death is in one place, and problems with said state (how much health does the player currently have) starts in that class and those who access him. Access control in this case refers to ensuring the PlayerModel only exposes methods to increment/decrement the Player’s hit-points vs. allowing them to be set to -16, or NaN/Nil, etc. You don’t even have to worry about this; you just don’t allow it to happen.

Thus, the burden on accessing and setting hit-points correctly is pushed to someone else; those who access PlayerModel. THIS is where you look for bugs, but again, you need to ensure only a set few have access to the data access layer (PlayerModel).

In short, Models centralize data access, ensure it’s correct, testable, and DRY and prevent incorrect access errors, (i.e. global.playerHitPoints = “dude, pimp!”).

Preventing Testability

This third problem isn’t necessarily around unit-testing and TDD (Test Driven Development), but more around just ripping the class out, putting in a simple main.lua, and seeing if it works. If it has dependencies, they get dragged with it… and you have to instantiate and setup those guys. Suddenly quickly confirming some class or method works or not becomes a time consuming process that’s painful. If you can’t test something in isolation, you’ll have huge problems down the road isolating problems in a timely fashion.

Globals by their very nature are’t testable because they’re variables, not encapsulated classes. While Lua has some neat mechanisms to encapsulate globals in certain contexts, somewhere, someone is setting a global to some value in their own way. If a class depends on this global, that global must be set the same way before you test the class that relies on the global. Since you may not know who set the global a certain way, that global may not be the same in your test environment vs. in the game proper.

Global Conclusions

While globals in Lua are fast, formalized, and accepted, you must be aware of the rules so you can break them with confidence. First, keep in mind if you want to get something done, premature optimization is the root of all evil. With that in mind, ask yourself the quick question: Does creating a data access control class/layer around your globals to ensure it’s DRY and secure add so much overhead that the speed makes your game un-playable?

I’ve found this not to be the case in my implementations in Lua and ActionScript. They run fine, are encapsulated, and succeed in good access control. Thus, while globals are accepted in Lua, implementing a good coding practice via a data access layer does not adversely affect my performance while increasing my productivity in DRY’er code that’s easier to test with good encapsulation.

Messaging Dependencies

We’ve seen how globals can work to allow multiple View’s to talk to each other directly or indirectly via variables they all reference, or even methods/tables. We’ve also see how this leads to bad things like harder to find bugs and spaghetti code (you change 1 thing that adversely affects something else seemingly unrelated) as well as making refactoring more challenging than it needs to be.

One way to allow encapsulated objects to communicate is through messaging systems, also know as notifications or events (we’ll just call them events because that’s what ActionScript and Corona use). When something happens inside the object, such as a user clicking something, or some internal property changes, it’ll emit an event. There are 3 types of events we’re concerned with: local, global, and event context.

A local event is an event issued from an object/table. In ActionScript, anything that extends EventDispatcher, including DisplayObjects (things you can see), can emit events. In Lua, only DisplayObjects can; you have to build your own for regular tables as Lua doesn’t have an event system. So, if I create a wrapper table in Lua, I can then register for events from that table, and later when it emits them, I’ll hear them. Those are local events; events dispatched from an object/table directly. Although event objects/tables have the target property on them so I know where they come from, USUALLY event responders are not that encapsulated, and make the assumption that the event is coming from a specific object/table.

A global event is one that’s received, but we have no clue where it came from. At this point, we’re inspecting the event object itself to find context. If it’s a collision, then who collided with who? If it’s a touch event, then what was touched, and how? Global messaging systems are used for higher-level events and concerns. While you usually won’t have global events for touches because your mainly concerned with handling the touch event locally, a pause event for example could of been issued from anywhere, and while you don’t care who issued it, you’re more than capable of handling it (stopping your game loop, pausing your player’s movement, etc).

To properly handle an event, we need context. Context is basically the data the event, or message, has stored internally so when the handler gets it, he knows how to handle it. If the event is a touch event, cool, start moving. If it’s a touch release event, cool, stop moving. If it’s a collision, is it a bullet? If so, take less damage than say a missile hitting. Is the bullet’s velocity higher? If so, take more damage than usual. This context is what allows the encapsulation to happen. You issue a message, provide context, and whoever gets it doesn’t necessarily HAVE to know where it came from; they’ll have enough information to know how to handle it.

For Corona DisplayObjects, this is easy. You just use dispatch an event. But for Model/data access objects, not so much. You don’t want the overhead of a DisplayObject to just to send messages, so you build your own. This implies another class/table with the capability of sending/receiving messages. This means your classes will have a dependency on this object. For example, if I want to test my Model class in a brand new main.lua, it’ll bring along/require the messaging class. This is a dependency. One of the threads (just like OOP, encapsulation, keeping things DRY, don’t optimize too early, etc) you want to keep in the back of your head is to keep the dependencies low. You don’t want a class to have too many dependencies. Like globals, dependencies can cause spaghetti code, hard to test & debug situations, and overall just hard to manage code.

Corona makes the event dispatching dependency invisible with DisplayObjects because it’s built in. Not so for regular tables. Somehow, you have to put this dependency in every class. You can either create a public setter for it, and pass in an instance, or just reference a class globally in a base class. Both are a dependency, the latter just requires a lot less work and code.

Downside? It’s a dependency. You also force this implementation on everyone who wishes to utilize your class. If you make the messaging system events, 2 things happen. First, people using Corona get it because it’s the exact same API and functionality (excluding bubbling) that developers are used to. Secondly, it’s interchangeable and works with Corona DisplayObjects. The best solution would be to do Dependency Injection/Inversion of Control… but I haven’t figured out how to do this in Lua yet, and I’m not sure Lua supports metadata annotations. Considering it’s dynamic, you CAN inject things like this at runtime, but someone, somewhere has to do so. Why do so when every object requiring messaging needs the same mechanism? Thus, the pragmatic thing is to build it in.

Also, more importantly, DOES this messaging system add more performance overhead than using simple globals? To make the question harder to answer, can you make tighter coupling of your code and still get things done?

It’s been my experience, if you make things easier to use with less coupling, you’re more productive in the last 10% of your project. While coupling makes things easy in the beginning, it’s a farce; it has more than an exponential cost at the end.

Besides, you can always increase coupling easily; it’s removing coupling later that’s hard. If you need to optimize, great, you can. If not, great, no more work to do; you can instead focus on features. Usually, though, you’ll know pretty quick if you do iterative builds if a messaging system is making a huge performance impact on your game on not. The only surprises you’ll get is you spend days on something without a build. Do a small test, see if there is a noticeable difference. Sometimes you’ll have n-problems you won’t find till your game gets to a specific size which are unfortunate. An example is a charting component that works great building up to 5000 data points, but suddenly DRASTICALLY slows down beyond that.

These problems aren’t the fault of the API. If you take a step back, the “30,000ft view”, usually it’s the implementation that’s at fault, not the code itself.

For example, a little history lesson. Back when ActionScript 1 development was increasing in scope, we went through 4 different messaging systems. The first was the built-in one for Mouse and Keyboard, etc. It was only partially available; there wasn’t a MovieClip one. So, we used ASBroadcaster; an undocumented one inside of Flash Player. It had a known bug with removing a listener during a dispatch, and other things. Then Bokel released a version on top of that fixed it. Then Adobe created EventDispatcher, mirroring the ECMA one. They then built this into the Flash Player for Flash Player 9′s new virtual machine.

There were others that came out after ActionScript 3 was born. PureMVC had notifications in it for an easier port to other platforms & languages. Robert Penner created Signals for a light-weight, object poolable, quick to develop in C#-esque messaging system.

As you can see, why the bottleneck for most larger Flash & Flex 1.x applications at the time was EventDispatcher, even when they built it into the runtime in C, developers opt-ed for a slower system built by themselves to solve different problems.

So why the continuous talk about performance questions in this section when I rail against premature optimization? Because messaging is the core of any app, or game. The choice you make is the largest impact on what you’re building, both from performance and from a development perspective. Yes, you can just use direct access to objects, or callbacks, but that’s not very encapsulated, nor DRY, and is a pain to re-factor later if you need. Messages via Events are more encapsulated, and less coupled, but have a performance impact. Additionally, only DisplayObjects use the internal C implementation; your own uses interpreted Lua with whatever JIT’ing/machine/voodoo conversion Corona does.

Traditionally, it’s easy to switch to events from callbacks, but not the other way around. While the performance impact isn’t that large to utilize a DisplayObject and use the built-in event messaging, based on some benchmarks, this isn’t a good idea to build upon.

Mediation

The third option is using the Mediator pattern. Once you have 2 encapsulated objects that need to talk to each other, you utilize a class that handles the communication. It takes the message from ViewA and sends that to ViewB. When ViewB wishes to talk to ViewA, it sends the message and the Mediator relays it.

All the MVC/MVP articles go over A LOT about the different things a View should/should not do, particularly with it’s needs for data and how to show it. Regardless of the implementation, it’s generally understood that someone such as a Mediator or a Presenter handels the responses from a View. If it’s a Presenter, it’s a dependency in the View, and the View calls methods on it. This allows the actual logic behind both responding to View user gestures (like when I touch a button on the phone) to not muddy up the View (muddy up means TONS of code that has nothing to do with displaying graphics, putting into groups, setting up Sprite Sheets, etc), and allows you to test the behavior in isolation.

Mediator’s are similar, although, the View has no idea he/she has a Mediator, and the Mediator has the View reference passed into it by someone else. Again, more encapsulation, yet SOMEONE has to have the burden of setting up this relationship. In ActionScript this is easy; Robotlegs just listens for the Event.ADDED_TO_STAGE/REMOVED_FROM_STAGE events and creates/destroys based on an internal hash/table. In Lua, you don’t have any DisplayObjects events, so you have to manually do it.

Either way, if you DON’T Mediate your View’s, you’ll eventually have a lot of code in there that has to “know” about other objects. This’ll be either a global reference, or a dependency… and we’ve already talked about why those things are bad to do. Additionally, tons of code in general is bad; having a View just focus on graphical things and emitting events people outside would care about while the logic can be put elsewhere makes it easier to manage. When you open a View class; you know pretty quickly what you’re looking at is just GUI specific code.

There’s another more important aspect of Mediation that is similar to messaging and that is system events that affect Application Logic.

For example, many things in a game care about a Player’s health.

  • the Sprite that represents the player; it needs to show different graphics for how much health it has
  • a health bar at the top right of the screen that fills up with green the more health the player has
  • sounds that play when the player loses and gains health

If you use globals, you’d have all 3 handled by the actual Player sprite class. It’d update it’s internal health and update the global variables. Those who have references to the globals would be informed when that value changes. Additionally, you’ve now wired them together if you do this. If you change one, you’ll break the other.

Using a Mediator allows:

  • the player and the health bar both the capability to react to the change in the hit points in an encapsulated way. If you change how the Player and HealthBar look/work, the actual logic on how yo do that is centralized to either them, or their Mediators… and usually Mediators are like 1 line of actual code to change.
  • The application logic of how hit points are updated and changed to be done in 1 place. As your game grows and different enemies need to do different types of damage to your player, and sometimes react differently depending on how much health the player has, this is all done and updated in 1 place. It’s DRY, and easy to find where the logic bugs are.
  • A side effect of this is… the Mediator pattern (lolz). You can have View’s the capability of talking to each other without having tight coupling.

The most important feature is solving the classic race condition of is the data ready for a View when he’s created, or is it null and he has to wait. Using Medaitors, you don’t have this problem. In the onRegister, you just set it if you have it on whatever Model(s) you need, else just wait for the Model(s) to be updated and inform the view.

…I wouldn’t say totally solved; handling “null” or “nil” is still a challenge for developers even in simple View’s. Those are good problems to have, though vs. race conditions.

If you enter the optimization phase of your game and want to remove events, use callbacks, and have hard-wired references, that’s fine if benchmarks truly identify that you need the performance gains. Usually, though, Mediator communication isn’t your bottle neck, it’s collisions, lack of object-pooling, and how messages are handled.

Quickie on Commands

Commands are just formalized Controller logic. In fact, in other frameworks, they’re simply Controller classes with methods. They’re called “Commands” because they do 1 thing… and can potentially undo it. If you’ve ever used an Adobe Product, a few of them like Dreamweaver, Fireworks, Flash, and Photoshop will have a Command list, also called “History Panel”. In Flash and Fireworks, you can even get the code for these Commands. The line blurs here once you lump them all together, but in my experience, good Controllers have 2 things in common:

  1. They contain the only code in the application that updates the Models (update/delete in CRUD for internal data)
  2. They contain all application logic… or at least share the burden with the Models.

For #1, this is important in tracking down bugs and keeping your code DRY. You always know who’s changing your Player’s hit points, who’s actually applying your level up rewards, etc. If you can test your Models in isolation, and they’re good… then you know who to blame. This is good because again, they tend to often start by being 1 line functions with the potential to grow to 30 to 60… not a bad way to start life, nor grow. Small, readable code.

For #2, whether you have a Controller class function, or a Command, SOMEONE in your application needs to “load the level data” from your level editor. SOMEONE needs to handle the fact that your player just drank a health potion, but he’s also wearing a Ring of Health Boost + 2, and this positively affects the effects of the health potions she drinks. SOMEONE needs to handle calling the loadSaveGame service, ensuring it worked, and updating all the Models with their relevant Memento data.

This orchestrator of pulling everyone together, to read multiple Models and “make decisions”, they’re the brains of your application. For performance reasons, a lot of Controller logic is often done directly in game views, even if it just references a Controller class for ensuring logic is somewhat DRY.

There’s a lot of loathing in the community by those with a more pragmatic bent, or just on smaller code bases with shorter deadlines. The overhead associated with them completely negates their perceived value when you can just call a centralized Controller logic function via… a function call vs. some event that magically spawns some other class that has 1 function with a bunch of injected dependencies. Just depends in you read that last sentence and go “Makes sense to me, don’t see what the issue with it is… ” or “w…t…f… why!?”.

Conclusions

Remember, the above is all complete bs. If you or your team have a way of building games that works for you, great. This is just helpful tool I’ve found in Flash & Flex application development, and it seems to help me in Corona games, specifically around the GUI/HUD portions. I still have globals in my collision routines for speed purposes, hehe.

Additionally, it’s a great teaching tool, too. Joel Hooks got some similar schlack like I did in using PureMVC when he was first starting out in Objective C for iPhone. Providing a comfortable & familiar framework of development really helped him learn and have context how the new language & platform work with certain concerns; it’s how he shipped his first app on the app store. Same with me in Corona… and game development.

Finally, this isn’t an all or nothing approach. You can just use it on the parts you need, or perhaps just to learn. I find its helped me learn a lot about Lua and Corona, as well as having the flexibly to change the API of my Player and Enemies without affecting how the GUI itself around the game works. In true spirit of total disclosure, I’ll report on any adverse overhead if I find it.

0
Your rating: None

In the Java community there's been a rush of lightweight
containers that help to assemble components from different projects
into a cohesive application. Underlying these containers is a common
pattern to how they perform the wiring, a concept they refer under the
very generic name of "Inversion of Control". In this article I dig
into how this pattern works, under the more specific name of
"Dependency Injection", and contrast it with the Service Locator
alternative. The choice between them is less important than the
principle of separating configuration from use.

0
Your rating: None

The following is a quick start guide on how to get RobotLegs working on top of the Gaia Flash Framework written by Steven Sacks.  In later articles, I’ll show how to use per-Gaia-page Contexts, a visual example, as well as cover Enterprise scenarios.  For now this should get you up and running in 10 minutes.

What is RobotLegs?

RobotLegs is a MVCS framework for Flex & pure AS3 applications.  You can use with Flash as well.  I call it PureMVC done right.  She’s still not at version 1, but is really close (docs in progress).

What is Gaia?

The Gaia Flash Framework is the Ruby on Rails for building Flash websites.  You can code generate your entire Flash website in seconds.  It has modules, SEO, page navigation, and deep-linking all built-in, amongst other things.

Why?

Gaia is great for building websites, but it’s just a platform for you to build on, a bunch of helpful scaffolding; it doesn’t prescribe a way to build your applications.  Specifically, you have to write your own code for Business logic and Application/Domain logic.  You still have to write code to hit back-end services, parse the returning XML/JSON/AMF, and act on that data.

This is where an application framework like RobotLegs comes in.  You’re domain model goes in the Model classes, your Business logic goes in the Service classes, and your Domain/Application logic goes in your Commands & Mediators.  You setup your shiz in your Context class(es), like PureMVC’s ApplicationFacade

Gaia builds your site, and RobotLegs makes it work with dynamic data.

Requirements

Before we get to the “How”, you need to know 2 requirements first.  This may scare some people off.

  1. You need both mxmlc & Flash CS4 or CS3
  2. Your application must be AS3

RobotLegs requires compiling in mxmlc because of the custom metadata tags.  Flash CS3 & CS4 do not currently support the -keep-as3-metadata mxmlc compiler parameter, thus, you must compile your RobotLeg’s implementation code using mxmlc (via Flex Builder 2, 3, Flash Builder 4, FDT, FlashDevelop, etc.).

While you can compile Gaia to an SWC in Flash CS4, and then re-compile via a Library linkage in mxmlc, this defeats the purpose of using the Gaia workflow in Flash.  I understand this is deal killer for many automated build/continuous integrations of Enterprise applications, so I’ll cover optional build scenarios in a future article.

Flash CS4 is required because it allows you to link to external libraries, in this case, Flex created SWC’s.  You could utilize Flash CS3, and just add a class path to the RobotLegs classes since you’ll typically only be using the interfaces in your Flash/Gaia specific code.  Both Flash CS3/CS4 will be exporting AS3 code since RobotLegs is for AS3, so you can’t use Flash 8 and export to AS2.

I currently do not have access to Flash CS5 alpha/beta to determine if it’s integration with Flash Builder 4 demoed at MAX 2009 would help in this instance, nor do I know if it can -keep-as3-metadata.

Quickstart Preface

The Quickstart may appear intimidating at 15 steps.  If you know Flex Builder/FlashDevelop, Flash, Gaia, and RobotLegs, you’ll do just fine, it’s not that bad.  Additionally, you only need to do this stuff once.

The rest of your project, you’ll spend in your code editor.  You can also link the Main file in Flex Builder to get code hinting on it.  The only time you go to Flash is to do Control + Enter.

GIT-R-DONE!!!11oneone

Quickstart

1. Setup your Gaia site.

2. Open up your main.fla in Flash.

3. In Flash CS4, go to File > Publish Settings, click the Flash tab, click the Settings button next to AS version, click the Library Path tab, and link to the RobotLegs.swc.  In Flash CS3, just add a class path to the RobotLegs source code directory.

flash-lib

4. Save your main.fla.

5. Create an ActionScript 3 project in Flex/Flash Builder, FDT, or FlashDevelop.  Point it to the same directory your Gaia project lives.  I suggest changing bin-debug to bin since that’s what Gaia uses.  Although it’ll generate a SWF, it’s hereafter referred to as a “module” SWF since Gaia will load it in and use it’s pre-compiled classes.

6. Create your own main class, differently named (ie not “Main.as”), and put next to Gaia’s Main.as.  This will be where your RobotLegs code lives.

project-dir

7. Link to the RobotLegs.swc as a Library.  If you are in Flex/Flash Builder, you may wish to link to the RobotLegsLib Library project instead.  If so, I put this in Gaia’s lib folder next to the FLA’s that Gaia puts there.  The image below shows linking to the Library Project.

lib-link

8. Create a “MainContext” ActionScript class where ever you’d like in your package structure.  Might I recommend something other than Gaia’s pages directory, like “com.company.project.robotlegs.contexts”.  In this class, you register your modules, in this case, your Gaia pages that actually need Mediators.  Here’s mine:

package com.jxl.gaiarobotlegs.robotlegs.contexts
{
        import com.jxl.gaiarobotlegs.pages.IAboutPage;
        import com.jxl.gaiarobotlegs.robotlegs.mediators.AboutMediator;

        import flash.display.DisplayObjectContainer;

        import org.robotlegs.mvcs.Context;

        public class MainContext extends Context
        {
                public function MainContext(contextView:DisplayObjectContainer)
                {
                        super(contextView);
                }

                public override function startup():void
                {
                        mediatorMap.mapModule('com.jxl.gaiarobotlegs.pages::AboutPage', IAboutPage, AboutMediator);
                        super.startup();
                }
        }
}

Notice the mapModule method goes “Your Gaia Page class as a String”, “The interface the Gaia Page class and the Mediator share”, and “The RobotLegs Mediator class”.  NOTE: In older builds of RobotLegs, they are using the fully qualified class name which is ::AboutPage, not .AboutPage (more info).  I have a hacked version locally which accepts a normal package path of “pages.AboutPage” vs. “pages::AboutPage”.  Yes, I’ve asked the RobotLegs authors to fix this.

9. Create 1 more class and 1 corresponding interface: a Mediator class for whatever Gaia page you’ll be mediating, and an interface of the same name with the I prefix.  Example: If you’re creating an “About Us” page for your site, you’ll probably have an about page node in your site.xml, and thus a corresponding FLA.  Create an “IAboutUs” interface, and an “AboutUsMediator” class that implements the interface.  Your Gaia “AboutUsPage” class will also implement the “IAboutUs” interface.  This is how RobotLegs will communicate to your Gaia code via the Bridge Pattern (more info on why).

Here’s the interface:

package com.jxl.gaiarobotlegs.pages
{
        public interface IAboutPage
        {
                function setAboutText(value:String):void;
        }
}

Here’s the Mediator:

package com.jxl.gaiarobotlegs.robotlegs.mediators
{
        import com.jxl.gaiarobotlegs.pages.IAboutPage;

        import flash.events.TimerEvent;
        import flash.utils.Timer;

        import org.robotlegs.mvcs.Mediator;

        public class AboutMediator extends Mediator
        {
                [Inject]
                public var aboutPage:IAboutPage;

                private var timer:Timer;

                public function AboutMediator()
                {
                        super();
                }

                public override function onRegister():void
                {
                        timer = new Timer(3 * 1000);
                        timer.addEventListener(TimerEvent.TIMER, onTick, false, 0, true);
                        timer.start();
                }

                private function onTick(event:TimerEvent):void
                {
                        timer.stop();
                        timer.removeEventListener(TimerEvent.TIMER, onTick);
                        timer = null;

                        aboutPage.setAboutText("Blah blah blah,nthis is from RobotLeg's 'AboutMediator'");
                }
        }
}

Thing to note in the above is the Dependency Injection via the [Inject] tag does IAboutPage vs. AboutPage; this ensures mxmlc doesn’t attempt to compile Gaia code into your module SWF.

10. Any events your Gaia About Us page will emit, put in the IAboutUs interface.  Any data your Gaia About Us page needs to have set on itself, implement a setter or a method in the IAboutUs interface.  This’ll ensure your About Us page class in Gaia and your AboutUsMediator won’t compile until you implement those methods, nor will your AboutUsMediator RobotLegs class.  Yes, I know events in interfaces aren’t enforced, but that doesn’t mean you shouldn’t do it.

Here’s the Gaia AboutPage class:

package com.jxl.gaiarobotlegs.pages
{
        import com.gaiaframework.api.*;
        import com.gaiaframework.debug.*;
        import com.gaiaframework.events.*;
        import com.gaiaframework.templates.AbstractPage;

        import flash.display.*;
        import flash.events.*;
        import flash.text.TextField;

        import gs.*;

        public class AboutPage extends AbstractPage implements IAboutPage
        {
                public var copyTextField:TextField;

                public function AboutPage()
                {
                        super();
                        alpha = 0;
                        //new Scaffold(this);
                }

                // called by RobotLegs's AboutPageMediator
                public function setAboutText(value:String):void
                {
                        copyTextField.text = value;
                }

                override public function transitionIn():void
                {
                        super.transitionIn();
                        TweenLite.to(this, 0.3, {alpha:1, onComplete:transitionInComplete});
                }

                override public function transitionOut():void
                {
                        super.transitionOut();
                        TweenLite.to(this, 0.3, {alpha:0, onComplete:transitionOutComplete});
                }
        }
}

Notice the implementation of IAboutPage.  Since Gaia FLA’s by default have “../src” set in their class path, it’ll share the same class path with your ActionScript project.  The only class it’s importing form that code, however, is the interface, which is a few 300 bytes or so once compiled into the SWF.  If you’re clever, you could use External Libraries in CS4, but that’s out of scope for this article.

11. Open up your main.as file in your editor of choice.  First, create a mainContext class reference, like:

private var mainContext:IContext;

12. Override init and do no call super.init.  Instead, write code to load in your RobotLegs SWF that your ActionScript project will create in bin.  You can use a Loader, your own wrapper class, extend Main to abstract away these details in a base class… whatever you want.  I used a Loader for this example.  Ensure you load the classes into the same ApplicationDomain so Gaia can share and use these classes, as well as any loaded SWF’s that need them.

var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
moduleLoader.load(new URLRequest('GaiaRobotLegs.swf'), loaderContext);

13. In your Event.COMPLETE function, snatch your MainContext class from the loaded SWF, instantiate it, and pass the stage in, and call super.init to let Gaia know you’re done, like so:

private function onComplete(event:Event):void
{
        const mainContextClassName:String = "com.jxl.gaiarobotlegs.robotlegs.contexts.MainContext";
        try
        {
                var mainContextClass:Class = moduleLoader.contentLoaderInfo.applicationDomain.getDefinition(mainContextClassName) as Class;
                mainContext = new mainContextClass(stage) as IContext;
        }
        catch(err:Error)
        {
                trace("Failed to find class: " + err);
        }
        super.init();
}

You use the stage so any DisplayObject added to the DisplayList will be checked to see if it has an associated Mediator.  Yes, I know OOP Purists will groan at this; don’t worry, I’ll offer a more pure solution later.  Remember, Gaia is typically used in Agencies with 2 week deadlines vs. 4 months; this is more than good enough for that crowd.

14. In your main ActionScript project class, define a dependency variable; this is strictly to ensure your RobotLegs code is compiled into the “module SWF”.  Assuming you have Build Automatically on in Flex Builder, it should make your SWF in the bin folder for you once you save.  Here’s mine:

package
{

        import com.jxl.gaiarobotlegs.robotlegs.contexts.MainContext;

        import flash.display.Sprite;

        public class GaiaRobotLegs extends Sprite
        {
                private var mainContext:MainContext;

                public function GaiaRobotLegs()
                {
                        super();
                }
        }
}

15. Test your Gaia project in Flash.

Conclusions

As you can see, all you need to do now is code all your code in Flex Builder (or editor of choice), and anytime you need to compile your site, you just go back to main.fla in Flash and hit Control + Enter.

You’ll also notice I create one “global” context here.  Reiterating, this is good enough for most design agencies as not every Gaia page will need a Mediator, and most Gaia pages aren’t that complex View’s anyway.

For the purists, in a future article I’ll explain how you can modify the Gaia template files, and configure your Context classes via the Gaia site.xml externally.  This ensures that the details of a Gaia page registering it’s own Context, or simply just creating a single Context + Mediator for itself, are self-contained and as strongly-typed as possible.

For those building Enterprise sized sites with automated build processes, I’ll later go into how you can integrate a Gaia site into your build process.

Thanks

Just a quick thanks to Steven for helping answer my Gaia architecture questions, and to the RobotLegs crew for helping me work out the details of how it could be done.

0
Your rating: None