Question

Wikipedia describes the Single Responsibility Principle this way:

The Single Responsibility Principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

The traditional use of the controller in MVC seems to lead a programmer towards a violation of this principle. Take a simple guest book controller and view. The controller might have two methods/actions: 1) Index() and 2) Submit(). The Index() displays the form. The Submit() processes it. Do these two methods represent two distinct responsibilities? If so, how does Single Responsibility come in to play?

Was it helpful?

Solution

Yes it does.

And if you want to follow the SRP, you disaggregate your Controller into a Dispatcher and Actions; the Dispatcher dispatches control to its actions, and at compile-time (C++ templates) or at runtime (Java XML, whatever), you'd compose Dispatchers and Actions.

Why don't we see this more often? Because Controllers are often "ad hoc" implementations, leaf-level concrete classes that aren't generalized and aren't meant to be subclassed. Here, the class is used more to conveniently group code, the actions are almost certainly non-public (likely private, maybe protected), "merely" internal implementation details.

The choice of how to decide what action to dispatch to, the number and diversity of possible actions, is high, and dispatching and action are tightly-coupled. So in practice, it's often easier to just put the code together in one place.

OTHER TIPS

No, it doesn't.

There is nothing inherent to the MVC pattern or its variations which lead to a violation of the Single Responsibility Principle. Whether the implementation of a controller violates SRP or not is based upon whether the encapsulated behavior has more than one reason to change (just as any other class), not because of any presupposed prescriptive use of the pattern.

The example you set forth is a subset of a basic forms over data application, where the controller is merely providing CRUD operations for a given model. CRUD operations are fairly cohesive in nature, so this generally doesn't constitute a violation of SRP. Where having multiple methods on a single controller start to become suspect is when the methods represent different behavioral interactions across the domain.

That said, even if someone where to argue that CRUD represents four separate non-cohesive concerns, there is nothing inherent to the MVC pattern that forces you to facilitate each of these actions within the same controller.

For a little history on the MVC pattern as well as some discussion of its application in Web development, checkout Interactive Application Architecture Patterns.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top