Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 881
Byron Sommardahl Avatar asked Apr 22 '10 23:04

Byron Sommardahl


People also ask

Why do we need controller in MVC?

A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.

What is SOLID principles in MVC?

SOLID stands for Single Responsibility Principle (SRP), Open closed Principle (OSP), Liskov substitution Principle (LSP), Interface Segregation Principle (ISP), and Dependency Inversion Principle (DIP). Here let's learn basics of SOLID design principles using C# and . NET.

Does MVC follow solid?

MVC follows the "S" of the SOLID principles by separating responsibilities. The model contains state information. The view contains the elements that interact with the user. The controller makes sure the sequence of steps occurs correctly.


1 Answers

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.

like image 70
tpdi Avatar answered Sep 20 '22 06:09

tpdi