Enumerable Objects in AS3

I’ve been meaning to post this for awhile, since it’s pretty useful but not explicitly explained in too many places. Sometimes you need to create a custom object to serve as a cache, stack, datastore, what have you. (Many times I use such objects to provide an API around a Dictionary). When you use custom classes like this, though, you don’t want to lose the capabilities of “for in” and “for each…in” loops.

Enter Flash Proxy. Extending the Proxy class allows you to implement for in loops with your own custom objects. The code below shows a proof of concept:

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
27
28
29
package
{
    import flash.utils.Proxy;
    import flash.utils.flash_proxy;
 
    public class EnumerableColl extends Proxy
    {
        private var _coll:Array;
 
        public function EnumerableColl()
        {
                super();
                _coll = [ 'test1', 'test2', 'test3' ];
        }
 
        override flash_proxy function nextNameIndex( index:int ):int
        {
                if ( index >= _coll.length ) return 0;
                return index + 1;
        } 
 
 
        override flash_proxy function nextValue( index:int ):*
        {
                return _coll[ index - 1];
        }
 
    }
}

Using Timers for Fun and Profit

Asynchronicity is a fact of life for Flex developers. Managing stateful interactions on the client side while asynchronously interacting with code on a server is a tough mental challenge to overcome on any project, and the fact that Flex is single-threaded makes this task even harder. Using Responders and passing callback functions can greatly ease the process of dealing with async activity, but on my currrent project I’ve ended up making heavy use of a simple AS tool - the Timer class.

The most common example of async activity is that of waiting for data to load. With the codebase I recently inherited, there were several points in the application in which Commands needed to wait for server data to load on the client before proceeding. The previous developers had checks in place to see if data had loaded before acting on the next procedural code - but if the data hadn’t loaded, they just used “callLater” to delay the callback. Using callLater to deal with an aysnc return can be dangerous to your app’s health! The main cause for concern is that callLater doesn’t allow you to have any control over when exactly your async handler is called. callLater delays a given function until the next enter frame event (remember, Flex is running on top of the old Flash timeline of frames). Wouldn’t you rather have exact control over when your handler is called? And even better, the chance to add a timeout? That’s where the Timer class enters the picture.

Timers are actually quite simple to use. Just instantiate a new Timer, with an argument for the number of milliseconds you’d like to wait in between async checks. Then add an event listener to the timer - timer.addEventListener( TimerEvent.TIMER, asyncHandlerFunction ) - and start the timer with timer.start(). Now, your asyncHandlerFunction will be called every x milliseconds. Your check to see if data has been loaded can be placed in the handler. Even better, you can place a check in the handler to stop the timer and throw an error if a certain amount of time has gone by ( using the timer.currentCount property, which returns the number of times the timer has been fired ). Make sure to clean up after your timer in the handler function, since you don’t want a bunch of timers clogging up your app’s performance!

Again, in an ideal situation you would be using Responders or event callbacks when waiting for the result of an async operation, but oftentimes the real world prevents ideal coding solutions. Timers can present you a useful tool for dealing with those ugly situations where the best practice just isn’t possible.

Five Good Reasons for TDD

In discussing application architecture issues like those in my last post, a lot of Flex developers bring up the same point: “Well, yes dependency injection [or whatever issue] is certainly the cleanest approach, but it’s not the fastest. What benefit does that really give me? I don’t really worry about testing my views.” Well, here’s the thing: you NEED to start worrying about testing your views!! You might be able to avoid view / integration testing in an HTML app (since most of the logic is on the server), but there’s no way you can get away with that approach as a Flex developer. Think about it: how much of your code is in your views, or directly related to your views? Not testing your views (or worse, not testing at all) is a recipe for some serious trouble.

The problem, of course, is that testing views is HARD. And it’s even harder when you’re writing tests to cover existing code. This difficulty has made me become a big fan of TDD, or Test-Driven Development. In TDD, you write your tests first, write your code second. Your development process becomes: “Write test. Watch test fail. Write code to make test pass. Refactor. Repeat!”

I was initially pretty skeptical of TDD: if the only benefit was increased test coverage of my code, I wasn’t convinced that I wanted to add another barrier for getting code done. But as I’ve started down the path of testing first, I’ve discovered a number of benefits:

(more…)

Roll your own Dependency Injection

At this point, there are more Flex frameworks floating around the internet than I can even count. Cairngorm is still the major player in the space, but it seems that lately all the buzz has been around Mate. I’ve used Mate for a couple projects at this point, and it’s easy to see why it’s so popular - tag based event mapping and dependency injection are a joy to use. But this isn’t a Mate post, so the details on that will have to come later!

Oftentimes it’s simply not feasible to re-architect an application from one framework to another, but if you’re “stuck” using Cairngorm on a project, it can be hard to leave the joys of Mate’s dependency injection behind. (IMHO Caingorm gets a bad rap for the anti-patterns that people often employ through it; after all, frameworks don’t make bad code, developers make bad code). But with a little bit of reverse engineering from Mate’s source, it’s easy to add dependency injection into any existing app. See the code in action after the jump…

(more…)

BreakingObserver for Conditional Debugging

Have you ever been debugging a Flex app to watch for a certain value while iterating over data?  A few months ago I had to look for two values as the code iterated over a passed array - with a length greater than 30. With my 2 values falling randomly in that list of 30+, my breakpoint on setting the value didn’t really help: I ended up pressing the play button over and over again. Of course, the mindless moving forward made me occasionally miss the value I was looking for in the first place, which made the whole process even more annoying.

A conversation with Adam Flater over Twitter prompted me with a solution to this vexing problem: borrowing from the util Observer class to force entry into the debugger. The Observer is a pretty common util function, which you can see in the source code below. I just needed to extend the Observer such that it would break when the watched object equaled a certain value. Enter the BreakingObserver:

(more…)

The Trouble with Feed Readers

Up until recently, I completely depended upon my rss reader to stay up-to-date on all my blogs. I had experimented with several readers over the course of the last few years, but had settled on Google Reader for its easy syncing and ability to share items with friends (although I’ve always found the UI to be lacking). I follow quite a diverse set of blogs and other sites - Flex blogs, of course, but other coding blogs across the programming community, web design sites, political and economic news and commentary. Any time I came across a site with content I really enjoyed, I added it to my reader.

As I’ve added sites to Google Reader more recently, however, I’ve come to a surprising realization: I’m finding it harder to digest content from within the reader than without. That is to say, I take less meaning from reading the same content in my reader versus on the source site. I’d attribute the change to the dramatically improved design and functionality I’m seeing from bloggers across the web. Reading posts on a source blog provides two features that Google Reader does not: complimentary design, and elucidating context.

Complimentary Design is pretty elementary: bloggers are making much better use of everything from headings and code blocks to well-implemented CSS code. Check out the two snippets of code from a recent entp blog post on Git.

(more…)

Blogging via TextMate?

I’m testing out a new workflow for blogging - blogging locally in TextMate, saving posts either as gists or a git project on GitHub, and posting to Wordpress via the TextMate blogging bundle. I like the idea of versioning my blog posts and keeping a local copy. We’ll see how functional / useful the whole process is!

Tools of the Trade

Now that I’ve been freelancing for awhile, I’ve come to rely on a few tools that I use every day.  I don’t have a workflow perfected yet, but the tools below go a great way to helping me work as efficiently as possible:

Harvest

Harvest

Harvest

For any new business, it’s CRUCIAL to get your finances up-and-running as quickly as possible.  I can tend to be disorganized with filing financial information, but Harvest allows me to manage everything I need - from time tracking to project financial management to invoicing — in the easiest way possible.  Harvest’s interface is incredibly responsive, clean, and intuitive.  Go check it out: they offer both a 30 day free trial and an indefinite free plan.

Unfuddle

Unfuddle

Unfuddle

Unfuddle is THE tool for software project management (in my opinion, anyway). It’s pretty much like Trac, but with a sexier UI and (most importantly) it’s hosted, so you don’t have to worry about configuration.  It allows for both SVN and Git repositories, so it’s a great alternative if you’ve started down the Git path of goodness. Once again, payment is based on a collection of plans, with a free plan for those just experimenting.

Evernote

Evernote

Evernote

Evernote pretty much serves as my second brain.  With both Win and Mac native apps, a web interface, and a glorious iPhone app, I can take note of ANYTHING that requires filing - whether a good article, a technical approach, or a long-term todo - and upload it to Evernote. Later, I can catalog it for future reference. This app is seriously killer. (And FREE!)

To-Done List

No web app here — this is as low fidelity as you can get! I’ve tried pretty much EVERY option for managing my list of action items, from basic to-do lists, to every manner of Getting Things Done apps (both web based like Backpack to Mac native like Omnifocus and Things). At the end of the day, none of these worked THAT well for me — but a “to-done” list works perfectly. Basically, a to-done list is a 3×5 card that I keep with me over the course of the day, on which I write down every task that I complete.  As I complete tasks, I usually will add a few immediate follow ups that I’ll need to get done that day, as well.  This system works perfectly for me, since between my head, Evernote, and tickets from Unfuddle and Trac, I already know everything that needs to get done in a day. While I would find myself daunted and even paralyzed by massively long to-do lists, to-done lists fuel my day and keep me energized and productive. (And of course, this is free too)

Has anyone else used the to-done list approach, or have any tips for using these or other tools?

Another Econ Break: Brains and Money

I think a true understanding of how the economy works requires certain leaps of cognitive logic that are somewhat difficult for our primitive brains to make. I remember the shock I felt when I first realized that stocks are priced not by some orderly system, but by insane auctions held on exchange floors with buyers and sellers screaming prices and quantities and trading billions of dollars.

But I think there’s one central leap to make in order to understand economics:

money, like information but unlike material objects, can be made to exist in more than one place at a single time.

For more, see George Dyson’s interesting article “Can You Have Your House and Spend it Too?” here.

Econ Break: The Unholy Trinity

A central theory in international economics is that of the “Unholy Trinity”, or “Impossible Trinity” depending upon whom you ask.  Basically, the theory of the “Unholy Trinity” is that countries can have only two of the following three characteristics at the same time:

  • Free capital flows
  • Independent control of monetary policy
  • Fixed exchange rate

In honor of economist Paul Krugman’s recent Nobel prize nomination, I’ll let him explain further (from 1999, to provide context to his examples):

The point is that you can’t have it all: A country must pick two out of three. It can fix its exchange rate without emasculating its central bank, but only by maintaining controls on capital flows (like China today); it can leave capital movement free but retain monetary autonomy, but only by letting the exchange rate fluctuate (like Britain–or Canada); or it can choose to leave capital free and stabilize the currency, but only by abandoning any ability to adjust interest rates to fight inflation or recession (like Argentina today, or for that matter most of Europe).

(You can find out more from Wikipedia.)

I’ve been thinking about the Unholy Trinity a bit in light of the current global economic crisis. We certainly don’t have an independent monetary policy, with central banks across the world making concerted efforts of injecting liquidity into global markets and the G7 coordinating policy decisions. Meanwhile, capital in Western economies has become extreme liquid (at least until the recent credit freeze).

As the Unholy Trinity would predict, currencies are certainly not fixed, but interestingly, countries have somewhat “pseudo-fixed” their currencies in relation to one another. Yen-Dollar almost always falls within a certain interval; same with Pound-Dollar and Euro-Pound, etc. But the recent crisis has thrown relative currency valuations completely out of whack. It will be interesting to see if maintaining a “pseudo-fixed” currency will become a priority that trumps the latter two components of the Unholy Trinity; if so, I’d predict an increase in regulation that slows global capital flows / limits liquidity.

Tweets