Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping a controller thin (too many action methods)

Tags:

I'm working on my first real ASP.NET MVC project and I've noticed that the controller I've been working in is getting rather large. This seemingly goes against the best practice of keeping your controllers thin.

I've done a good job keeping the business logic out of the controllers. I use a separate layer for that. Each action primarily calls a method in the business layer and coordinates the end result based on whether or not the modelstate is valid.

That said, the controller has a large number of action methods. Intuitively, I would like to break the controller down into sub-controllers but I don't see an easy way to do that. I could simply break the controller down into separate controllers but the I loose the hierarchy and it feels a bit dirty.

Is it necessary to refactor a controller with a large number of thin actions? If so, what is the best way to do this?

like image 253
Mayo Avatar asked Sep 28 '10 13:09

Mayo


People also ask

Can you overload action methods?

A method used as a controller action cannot be overloaded..

How many lines should a controller be?

If your controller actions are more than three or four lines long, they may be doing too much. It might help to remember the primary job of a controller, to handle parameters, delegate to business objects then format any results.

Can a controller have multiple models?

Answer: yes. Create a wrapper model, put other two models in it.


1 Answers

First, when you hear that it's good to keep controller code to a minimum, this mainly refers to keeping each action method as thin as possible (put logic instead into business classes, not into Views and ViewModels.) It seems you're doing this, which is great.

As for having "too many" action methods, this is a judgment call. It could actually be a sign of good organization, that you're having each action focus on one thing. Also, maybe you're using actions specifically for use with RenderAction? And, it could just be the nature of your solution that there are many things to do relating to your Controller's theme.

So, my guess is that you're probably fine. However, to make sure, on note paper break out the controller into 2 or 3 controllers, and sketch out how your stories would work moving from action to action. And if you find that your workflow works with more controllers, you should break it out. Especially if you're going to be adding to this functionality later. The sooner your break it out the better.

like image 178
Patrick Karcher Avatar answered Nov 20 '22 01:11

Patrick Karcher