2008-03-24 16:30 UTC URLs do not belong in the Views
It's bothered me for some time to hardcode URLs in my views. It means that if I want to revise the linking structure, I may need to modify the views in a huge number of places. At the same time I don't like the thought of putting it in the model either.
In the entry Enforcing Strict Model-View Separation in Template Engines I point to an interview with, and a paper by, Terence Parr that articulated this issue much better than I had fleshed it out in my mind.
He also proposed a solution: Introduce an extra layer - Renderers - that turn model objects or attributes into a displayable format. An example might be formatting a date string the appropriate way.
His work is centered on Java, and so the solution he proposes (see section 8.1 in his paper) is suggesting having the controller wrapping attributes of the model in separate objects. This is clearly the most flexible solution, in that it allows different controllers to provide different renderers, or use different renderers at different times.
How does this apply to the URL issue? It would be trivial to wrap model objects with a renderer who knows how to turn the model object into a URL referring to it. As an experiment I tried extracting the URL's for the Ruby app running this blog, and it showed me two things:
- It's certainly doable.
- It's a useful exercise even if I ultimately don't make the change, in that it exposed areas where I clearly hadn't thought the linking structure through very well - especially it made me notice areas in my admin code that could be made far more restful and consistent.
Does the URLs even belong tied to the model, and not in the controllers?
It's a tricky situation. On one hand, the controllers should handle the overall interaction. On the other hand, in all the web applications I've worked on the systems have been very data centric, and URL schemes have always revolved around the model. REST also favors a data centric approach. But this is less of a problem than it might seem at first if you first employ separation of concerns by clearly handling the URL formatting either in a separate renderer class or as a separate aspect of the model classes through reopening the classes. Especially if you pass a renderer (or wrap the model objects that gets passed to the view in a renderer object), the controller remains in the driving seat completely. Imagine an API like this for the view:renderer.url(some_model_object)Interesting opportunities does open up to tie this to the routing and still relatively loosely couple the classes. In fact, I would argue that a method like this reduces coupling between the controller and views: If you put URLs in your views, and you change the routing or what aspects are handled by what controllers, the URLs may change and the views may have to change with them. Contain the URLs in a rendering object passed from the controller, and you centralize those changes. If the routing mechanism is designed to do it, it could conceivably provide a rendering class if the routing information is extended somewhat. On this blog "/tag/(.*)" maps to the Tag model class, and the (.*) group refers to the "name" attribute of the Tag model. If the router instead of mapping /tag/(.*) only to a controller, also contained the knowledge of which model and attribute the static and dynamic parts of the URL map to (if any), then the rendering could be automated. Arguably, the router is part of the controller infrastructure (technically you'd call it a front controller) and centralizing limited knowledge of the model there is not a big concern, as long as this knowledge is provided by the application and not encoded in the routing component itself. To take an example from my current router for this blog, suppose I turned this:
map '/tag/(.*)', C::TagController map '/(.*)', C::ShowItem.. into this:
map '/tag/(.*)', C::TagController, M::Tag, :name map '/(.*)', C::ShowItem, M::Item, :url.. to denote that our hypothetical renderer should turn renderer.url(some_item_object) into "/#{some_item_object.url}" and renderer.url(some_tag_object) into "/tag/#{some_tag_object.name}" An alternative would be to change from straight regexps to something requiring a bit more parsing:
map '/tag/{M::Tag.name}', C::TagController... which also opens up the possibility of passing an already instantiated model object in to the controller. The downside of that route is that it requires the dispatcher to know how to create model objects, which either means it needs a factory or it would become tied to a specific mechanism for creating model objects. WIth that choice in mind the earlier syntax example seems more attractive - you trade a little bit of simplicitly in the routing for a whole lot reduction in coupling.
Comments
Why does this matter?
It matters because there's no reason to couple the two. You don't buy anything. The view only needs a lookup mechanism that is dependent only on the model. The controller doesn't need to know any of the details, but _may_ want to actually modify aspects of the rendering. An example of the latter, from actual projects I've worked on, is that it's not uncommon to want to explicitly re-route URLs via CDN's or redirect scripts. For a webmail app I worked on, we forced all a lot of links through a redirect because of stats requirements or to "wash data" out of the referrer URLs (Yahoo is an example of a company that's big on redirecting links - it has server farms dedicated to handle redirects). Webmail apps generally do the same for external links. Using a single mechanism to prevent accidental leaks from certain parts of an app is then a prudent security measure. For another service I worked on, certain parts of the model would in certain circumstances act as a proxy for an external resource, and when linking directly _some_ of the objects should link to an external URL rather than an app internal one. In those cases loose couple becomes valuable, because it allows the decision of how and whether to modify a mapping to be taken at any point in the chain without coordination - you just wrap the renderer object. Having the initial renderer generated from the routes is good. Tieing your model, views, or even controllers to a specific front controller or framework idea of what urls should look like is not. (As a side note, when actually revisiting the Rails routing, and looking at the code, I was pretty appalled at the amount of type checks I found, instead of capability tests - i.e. explicit checks for Hash and Array classes instead of checking for the API functions needed, but that's a separate issue)