Skinny Everything (Part 2 of 3)

Part 1 brought up the following fact about MVC frameworks: While it is very important to have a skinny controller, it is much better to have a skinny everything. If you didn’t read the previous article, know that while I am talking about Rails specifically, this concept applies to MVC in general.

The first method I wrote about was using Draper for Decorators, which is a nice way to keep display logic out of models without resorting to using helpers. This article will cover another method for getting skinnier:

Concerns

Concerns are modules you can use to extract code out of models and controllers. This is useful for various reasons. An obvious one is that this makes things skinnier, which we’ve already established is good. Another is that you can use these concerns to mix into other models and controllers, which can be especially useful when you have two different models that need to have some similar functionality.

When you start to notice that a model is getting too fat, check to see if it has a bunch of methods that are all related to one feature, responsibility, or “concern.” If so, it might be a good idea to break all of those closely related methods into one concern file, which you then include right at the top of the model. Then if something goes wrong with that particular functionality, it will be easier to locate the problem. An example:

You’ve got yourself a Product model. It’s pretty sweet, except that it’s starting to get a little fat. It turns out that about 200 lines of the model are related to search methods. So you decide to move all of the search related methods into a “ProductSearch” concern. Now the model is nice and clean, and you know exactly where to find all of the methods related to the search functionality. Down the line, however, it will most likely be necessary to go one step further; tweak the methods so it is a reusable concern, and call it “Searchable”. Then include the Searchable concern at the beginning of any model that you want to have that functionality.

For more on concerns, check out this great article by DHH: Put chubby models on a diet with concerns

Read Part 3 of this post here.

More Posts by Daniel Andrews:

Kubernetes, Delivered

Deploy your first app within 24 hours. Book a demo to get started.