MVC (Model-View-Controller) design pattern provides a great architecture for our applications. We all have heard “Fat models, Skinny Controllers” but is that really true? Well, the answer is not quite simple.
Web Applications are changing
Web apps have evolved so much in the past few years. It’s now so common to use third-party API, real time notifications, queueing systems, and etc. But, at heart all applications require their own business rules.
Why not Fat models, Skinny Controllers?
It’s a common thought that taking logic out of controllers and dumping it in models will make the controller skinny. Technically it will make the controller skinny, but the model gets cluttered and messy! So, what should we do?
Skinny Models, Skinny Controllers, and Service Objects
The goal is to avoid making one object do everything (aka. The God Object). Instead, dividing logic in smaller methods that hopefully do one thing. Not only those methods are easier to test, but also very easy to maintain. Service objects can help take care of a Model’s non-database driven methods and application logic. Service objects can also reduce code duplication because other objects can use its methods.
- Separation of concerns is your friend!
- Don’t be afraid of making classes and objects! They can help simplify your code.
- Use service objects for application logic
- Avoid Controller and Model bloat
- Don’t Repeat Yourself (DRY)
If you are in the Ruby world, I highly recommend checking out Practical Object-Oriented Design in Ruby (POODR), by Sandi Metz.