Does the traditional use of the controller in MVC lead to a violation of the Single Responsibility Principle?

纵饮孤独 提交于 2019-11-30 13:08:34

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!