Model, view or controller? June 14th, 2008

This came up on the rubyonrails-talk mailing list again, and it took me too long to find my answer from last time in the archives, so here it is.

Sometimes it's hard to decide which layer of an MVC application to put code in.

It took me a long time to settle on a simple decision process that works for me, especially in the J2EE environment where it's not as easy to change your mind.

I default to trying to push code down into the model. However, I ask myself these two questions:

  1. Does this code describe anything other than behavior of this model?
  2. Does this code know about CGI or HTML?

If the answer to either of those questions is yes, I look more seriously at putting the code in the controller or an helper. If the answer is "yes and no", I'm probably trying to do too much at once, and need to break it up across the layers.

In summary, favor the model, but not at the cost of layering violations.

The attitude that this comes from is that your domain model (your collection of "models") is the system. The controller is only there to mediate a view into it. This attitude works well for the kinds of applications Rails is suited to.

Here are two more considerations:

  1. Code that you put in the model is easy to use from the Rails console and runner. Code that's in the controller is more of a pain in the arse to get to.
  2. Model instances can call each others' methods, but they can't call methods on controllers without jumping through hoops.

2 Responses to “Model, view or controller?”

  1. beginers credit said on
    Nice Site! http://google.com
  2. Unessyceno said on
    omg.. good work, man

Leave a Reply