Controller Scope & Testing
Friday, September 25, 2009 at 12:19PM |
Kevin Rohrbaugh The transition from Web Forms to MVC can be challenging, and perhaps the trickiest aspect is controller scope. It’s rather easy for Web Forms developers, especially those who never adopted Model-View-Presenter (or similar patterns), to persist the bad habit of sticking too much functionality in page code-behinds by building massive, monolithic controllers in MVC.
My earlier post gave my thoughts on what a controller does metaphorically, but I came across a more concrete post about the same topic on Jag Reehal’s Arrange Act Assert blog. Skinny controllers are a key concept in MVC, and really shouldn’t be understated, so it’s a topic I’m likely to continue returning to.
Abstractly, it’s easy to talk about bloated controllers and how dangerous they are, but how do you tell when your controllers are getting fat? One way of detecting controller bloat is the difficulty encountered when unit testing them. As increased testability is a highly touted feature of ASP.NET MVC, many developers moving to it are also becoming interested in unit testing, some of which for the first time. If you find yourself staring at the Visual Studio code editor, contemplating how you should test your controller action methods, it’s highly likely that the controller is simply doing too much. Thankfully, Jag also wrote a good post outlining how to unit test controllers that’s worth your time.
Bloated controllers are likely to yield complicated, difficult to maintain code-bases, which can lead to the same problems encountered in poorly-designed Web Forms applications. Since avoiding such issues is often a catalyst for moving to MVC in the first place, it behooves developers to be diligent and avoid the practices that lead down the same painful path. Adopting a design pattern in name but not in principle won’t deliver the intended benefits and it is still all-too-possible to build a poorly-designed web application using ASP.NET MVC. In other words, the framework won’t rescue you on its own, real, sustained behavior change is necessary.
Put your controllers on a diet, and keep them skinny!
ASP.NET MVC,
Testing 
Reader Comments