views:

70

answers:

1

Controllers can become large and unwieldy when they contain large numbers of actions. Is this a significant problem in real-world use, and if so what are the strategies to mitigate it (or is is good enough to simply keep the action-count down per controller)?

Off the top of my head I can envisage the controller offloading the logic to action implementations in other types, grouped according to some meaningful heuristic.

+1  A: 

In my experience, this mostly happens when I don't apply the "REST" knife aggressively enough. Sometimes the metaphor is not consistent with the way we think about a problem; for example, it's easy to think that "login" is an action on "account", but if you apply the REST knife, you realize that logging in is really "starting a new session" and you invert the idea by applying a "new" (or Create) action on a SessionController. Then you have a small controller responsible for creating and destroying sessions (logging in and logging out).

I'm sure a few people will not be fond of muddying the REST waters with the messy concept of authentication, so let's look at a more obvious example. I can have a BlogPost entity, and it can have a bunch of comments. Rather than having an action AddComment on the BlogPostController, I have the usual create/edit/delete methods on BlogPost, and another controller CommentController whose new/create actions expect a BlogPostId, and implements create/edit/delete methods.

I've run into some situations where I needed a non-REST-like action, such as "import a list of X from a CSV file", each of whom belongs to a Y; the "list" isn't really important as a domain concept, as I'm really just trying to add to an existing collection of Xes. In that case, I took what I perceive to be a slightly ugly approach of adding an "import" action to my XController. That code is the messiest code in any of my controllers, and I'd be inclined to factor it out into something with more contained responsibility (an XImporter class, perhaps), but for now it "works." I'm sure someone more clever than me would have a better solution.

So my argument is this: If you have lots of un-RESTy actions, there's a kind of code smell; perhaps you aren't modeling what you're controlling correctly. But if you have say, 1-3 unRESTy actions and attempts to rethink the problem don't lead you in the right direction, perhaps it's not worth worrying about.

JasonTrue