Friday 12 December 2008

It's all about the resources

mine

Our new web application, codename Doyle, is being built on the ASP.NET MVC framework. The primary driver for this was enabing Test Driven Development for web apps. Increasingly frustrated with the brittleness of the traditional approach this represents a fantastic architecture for building robust web apps.

The big challenge however has been conceptual. Patterns the team are comfortable with, have turned out to be unsuited to this approach. Discussing one such question at the whiteboard yesterday, it occurred to me that the issue we were having was we thinking in terms of method based architectures rather than resource based.

To date, our approach has been to have thin Data Objects that are passed to facades and sub systems that perform operations on them. We're a messaging shop so I guess that's where it came from. A message gets passed around, operations are performed on it, decisions are made about it.

The term Controller implied a co-ordination role with knowledge of controlling one or more sub-systems. However MVC tells us that is bad, Controllers should be thin and Models should be fat.

A good example is our new send message page.

The first pass involved the controller iterating through the recipients, constructing message objects and passing them to the Esendex ReST API SMS Message Dispatcher via our C# SDK.

Very quickly the controller got fat, validation, error condition handling, suddenly it was squatting behind the view like a Sumo Wrestler tucking into his 7th chicken of the day.

The light-bulb moment was the realisation that rather than thinking about sending a message, we were actually sending a batch of messages. Enter the MessageBatch resource.

All the controller has to do is load up the MessageBatch resource with the parameters (recipients, body, etc) and call Send. This returns either true or false, successful or failed.

The controller then just has to make one decision go to one page if successful, or another if not. Safe in the knowledge that the MessageBatch object will be duly populated with an error/validation info required for the view to render and give the user the option of what to do next.

Yes this has just moved the logic to another part of the system but being in the Model layer gives the opportunity to refactor, inherit, and most importantly, mask the complexities of sending a message batch from the front end. We're comfortable unit testing and doing it this way forces as much logic as possible into units.

So, if you're making the transition to MVC then consider looking at some of the thinking behind ReST web services (I read: RESTful Web Services as a good primer). I've come to the conclusion that ReST and MVC are intrinsically linked.

Photo credit: alarch

No comments: