Monday, 2 March 2015

fat model, skinny controller in Ruby on Rails

“Fat model skinny controller” is an MVC-based Rails design pattern.

MVC is itself a software design pattern that separates a system into three separate and distinct layers; namely, Model, View, and Controller. MVC strives to ensure a clean separation between each of its layers through clearly defined APIs. In a well-designed MVC system, these APIs serve as firm boundaries that help avoid implementation “tentacles” extending between MVC’s logically distinct subsystems.

The “Fat model skinny controller” design pattern advocates placing as much logic as possible in the Model for (a) maximum reuse and (b) code that is easier to test.

That said, a common pitfall for Rails developers is to end up with “overly bloated” models by adhering too blindly to the “fat model, skinny controller” paradigm. The infamous User model is a prime example of this. Since many Rails apps are about the user entering data into the system, or sharing information with their friends socially, the user model will often gain more and more methods, eventually reaching the point where the user.rb model becomes bulky and unmanageable in size.

A few key alternatives worth considering include:
  • Use of other objects: Extract functionality out of models into other objects (such as Decorators or Service objects)
  • Hexagonal architecture for Rails: Employ a hexagonal architecture that views the application as a hexagon, each side of which represents some sort of external interaction the application needs to have.
  • DCI (Data Context Interaction): Instead of focusing on individual objects, focus on the communication and interactions between data and its context. 

No comments:

Post a Comment