MVC 中控制器的传统使用是否会导致违反单一职责原则? [英] Does the traditional use of the controller in MVC lead to a violation of the Single Responsibility Principle?

查看:13
本文介绍了MVC 中控制器的传统使用是否会导致违反单一职责原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

维基百科这样描述单一责任原则:

单一职责原则规定每个对象都应该有一个单一的职责,并且这个职责应该完全由类封装.它的所有服务都应严格遵守该职责.

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.

MVC 中控制器的传统使用似乎导致程序员违反了这一原则.拿一个简单的留言簿控制器和视图.控制器可能有两种方法/操作:1) Index() 和 2) Submit().Index() 显示表单.Submit() 处理它.这两种方法是否代表两种不同的职责?如果是这样,Single 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?

推荐答案

是的.

如果您想遵循 SRP,您可以将控制器分解为调度程序和操作;Dispatcher 将控制分派给它的操作,并且在编译时(C++ 模板)或运行时(Java XML 等),您将组合 Dispatchers 和 Actions.

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.

这篇关于MVC 中控制器的传统使用是否会导致违反单一职责原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆