This post will show you how to slim down the service layer in your Rich Internet Application after defining RESTful services.
Posts on REST usually begin by claiming that REST architecture involves much, much more than reducing the syntax of web services to database-derived verbs: create, read, update, delete (CRUD). That’s true, but for this post, exactly that supremely useful reduction will be “REST.”
This post won’t explain how to make a REST call or if it’s possible to wrangle http REST for Flex (no, yes with Rails and Flex, kinda with Java and Flex, StackOverflow). I’ll be focusing on RIA structure rather than http. Examples will be drawn from Flex, but my conclusions should apply to any stateful RIA whether Silverlight or Javascript-based, with any kind of services, whether http or rpc.
It might seem odd to think of a RESTful RIA. Whatever else it is, REST is a kind of service call. An RIA makes calls, but it shouldn’t depend on what kind of calls it makes. Wouldn’t that violate the separation of concerns whereby some particular logic is devoted to making calls, and other logic is devoted to other RIAish things like holding and displaying data?
Actually, it does. And of course that can be bad. If you code with the expectation of RESTful services, it will be difficult to repurpose that code when RESTful services are long available. Then again, there is no logical end to the encapsulation imperative. Losing some encapsulation might be alright if the payoff is high enough.
REST CRUDely Summarized
REST is rife with nouns organized by a very few, but strong and consistent verbs.
The nouns are “resources.” This in itself is not surprising. Anyone calling services is expecting access to something like a resource, some information, table, etc. What is surprising and characteristic about RESTful services is how consistently they define services in terms of noun-like resources.
Quick example: Everyone reading this has written or consumed a login service that looks roughly like this: loginService.login(username, pwd). A RESTful login service would look quite different, emphasizing noun rather than verb: session, not logging in. In REST-speak, logging in means creating a session, and conversely, logging off means deleting a session.
Creating RESTful web services entails speaking in noun. That’s natural enough for many services: accounts, members, etc. But it requires more imagination in those many cases that provoke a coder to reach for more elaborate syntax: accountService.findOverdrawnAccountsIn, memberService.restoreDefaultPreferences, user.getPresenceSharingOnlineFriends.
A REST service can define resources (OverdrawnAccounts, OnlineFriends) that do not necessarily map directly to one table, or any table, really. The service coder is responsible for creating an API, and the API is just what the coder wants it to be. (As this guy said to me when I was troubled about REST). The important thing is the nouns he offers up, not how they are assembled or constructed.
The mavens of prose style have always exalted verbs over nouns. The mavens of REST do exactly the opposite: they exalt the noun and excommunicate nearly all verbs. The essentials that remain are very simple verbs similar to database operations: Create/Read/Update/Destroy. Only slightly more verbose are the templated methods for controllers in Rails: index (for collections), show, edit, update, new, create, destroy.
A REST API is like a long shelf at a grocery store: flush with things neatly stacked…and with just a few magic verbs, you can manipulate them, replace them and delete them.
Slimming Down the Service Layer
REST architecture has many cosmic implications for the structure of the web and http. Frankly, being a Flash/Flex developer and more a front-ender, I don’t understand them. But as soon as I learned about REST, I realized how unnecessarily verb-ridden Flex projects can be.
In a typical Flex project, every consumed service requires a corresponding delegate class which spells out its various powers: login, createAccount, deleteAccount, etc. And in Caingorm or PureMVC at least, several different command classes might invoke this delegate class.
What I will now suggest should be screamingly obvious to anyone who has been coding Flex for more than a week: If your services are RESTful and your delegates use exactly the same verbs (index, create, show, update, destroy), they look identical. So why not create a single delegate class and parameterize it by resource? And then, why not use a single command class to invoke this delegate and do something boringly predictable with it, like stashing it in a ResourcesProxy or ModelLocator or some convenient storage? Wouldn’t that reduce paperwork?
There’s any number of ways to standardize. My still-evolving, project-specific implementation is this:
I am in no way stuck on this. This project happens to be using the PureMVC framework and amf transport, and in any case, this diagram will soon be outdated. The point is, if services are RESTful, you can invoke them in one place with a few strings:
ResouceProxy.doOperation(”member”, “update”, aMemberVO)
Likewise, when the service is returned, your local model can update in a completely stereotyped manner:
ApplicationData.doOperation(”member”, “delete”, aMemberVO)
ApplicationData.doOperation(”member”, “index”, memberVOs)
The advantage of reducing all your delegates to one delegate, and all your delegate-invoking commands into one command is obvious–less classes, less coding, less mistakes. It also increases the readability of your project. When you open up your controllers folder, for instance, you’ll know that every command class is applying its own particular torque rather than following a me-too, zombieish recipe: “Get delegate…get data…put…in…ModelLocator.”
One consequence of centralizing the access and storage of resources is that delegate-invoking commands no longer handle responder errors and view changes. Instead, in my set-up, ApplicationData broadcasts dynamically generated ResourceEvent types from a set of strings (”memberCreateSuccess”, “memberDestroyTimeout”, “memberDestroyErrors”, “noteUpdateSuccess”) along with associated data, and the application reacts to these events.
Integrating this kind of messaging into a PureMVC-based project is trivial. Mediators sign up to be notified about particular data events and are natural places to handle responses and direct the view. Most other Flex frameworks including Cairngorm are command-happy and lack formalized Mediators, but it is equally trivial to listen for a data event, then dispatch whatever magical event your favorite framework autowires to a target command.
This is one way to handle exceptional events (errors, view changes not automatically triggered by model changes). There are no doubt other, better ways. Again, the point is that treating services and data uniformly makes it possible to automate the conventional and treat the exceptional.
When to use RESTful RIA?
Obviously, it’s impossible in the majority of cases. RIA developers often don’t have control over the services they consume. The services are legacy, or created by another team. And most services are not RESTful. Also, mixing RESTful and non-RESTful service-handling wouldn’t be worth the trouble since the payoff for RIA REST comes from centralizing functionality.
But what if one is in a position to create the services and the RIA together, would it be worth it?
Not if your project is small or simple. In that case, the most agile approach would be to let the development of the interfaces drive the development of services. However, as a project grows more complex, the virtues of a RESTful API become more apparent.
Evangelists of REST like the Rails community preach the virtues of a RESTful API: its nounish services make it more human-readable, provide a convenient portal for delivering various formats (noun.xml, noun.amf), and protectively encapsulate the API by shielding it from particular syntactical demands.
This last virtue is of most interest to a parochial RIA developer like myself. I found that thinking in noun while working solo, on both the server and the client sides, on a medium-complexity RIA project did add overhead, but, over the long run, it paid off.
I didn’t waste time on syntax. I was able to generalize delegation and delegate commands so that adding any resource was a matter of one line. On the API side, thinking in noun kept the API fresh and elastic. Adding another resource was not trivial, but it did often build nicely on elaborations I made on the models to accommodate another resource. I tended to add resources rather than undertake extensive refactoring.
All in all, by depending on RESTful services and their severely limited syntax, I kept relations between the server and the client both distant and amicably simple. I’m now curious to know how a RESTful project would work out in a team environment, whether it would make the interaction of back enders and front enders more productive.
Beyond the VO
A deep challenge in treating your resources RESTfully is dealing with nested data. Here is a simple case: When a user logs in, a session is created and returned to the RIA. And typically that session would return a UserVO nested inside the SessionVO. Now suppose the user changes his password and updates it. What has to happen?
First, there needs to be a user resource defined. Second, the nested UserVO needs to go into this resource. Third, that UserVO needs to be throw at the sky and caught on the rebound.
So far I’ve handled this by defining the nested UserVO manually, then firing a Rails-style “after_filter” function in ApplicationData::doOperation that looks for “session,” and “create” parameters. When it finds the UserVO it puts it into its resource and points the user property of the Session there.
Over time I’ve filled this filter function–which is just a big switch statement–with small data alterations. A more ambitious approach would be recursively search for nested VOs when hierachical data arrives, then dynamically create resources for them and point their parents’ properties at them. Only extra-special alterations would occur in the filter.
As long as I’m finger painting, I wondering if a centralized, uniform treatment of data would make it easier to put some basic, practical questions to a VO that are now pretty frustrating:
Do you already exist here?
Does that empty property of yours point to a VO that already exists here?
Can you convert that id property into an actual nested VO?
It’s easy to normalize a database, less easy to normalize an API, RESTful or not. Duplicate VOs crop up. So it’d be nice if ResourceProxy was queryable. It would be even nicer if one VO was automatically forced to overwrite another VO in the ResourceProxy. Also, basic Rails-type associations–in which some kind of VO proxy could access ResourceProxy to find locally or retrieve remotely its VO’s empty properties–might be worth the trouble if the RIA consumed and updated a lot of nested data.
Holy Smokes, ALL of this (REST services automated, rudimentary ORM) and much more has ALREADY been done for Ruby-based projects: RestfulX by Peter Armstrong and Dima Beristau. And what a coincidence, the idea gestated in me after reading Armstrong’s Flexible Rails! I think I need to speed up my metabolism…and dive into this framework, which promises to be the first integrated, full-stack framework that includes Flex.

Matt, awesome post. I read the whole thing, and then looked to see who wrote it. Surprise, surprise. I know that guy…
Good work.
Posted by David Knape on April 15th, 2009.