Does the MVC pattern describe Roles or Layers? - model-view-controller

I read a text recently saying the MVC pattern describes the layers in an application. But personally I see MVC showing several key roles in an application.
Which word do you think is better, layer or role, to describe the three main pieces of MVC?

Layers should imply a very narrow coupling between the respective sets of code. MVC involves relatively tight coupling between the model, view, and controller. Therefore, if you characterize this as a layering pattern, it becomes problematic in terms of defining an API between the layers. To do this properly, you would have to implement some unintuitive patterns.
Because of this, I would agree with your tendency to view it as a pattern that defines roles within a single layer.

I think roles is a better description. The view and the controller are both in the same "layer" and usually the model is described as a layer but is used between layers.
Usually my applications are centered around the domain model with stuff like presentation, persistence and file-io around it. Thinking about an architecture as layered doesn't really work for me.

MVC clearly defines ROLES. these are 3 roles you can implement in any number of layers. For example u can have a multi layer controller

Roles, not layers. Layers are completely dependent on the underlying implementation of the MVC pattern. For instance, a service layer may be a single layer on one implementation, but it could have a web service remoting layer and a database layer (for two differing service layers) on another implementation. The concept of layers is just to help you organize it, as is the pattern, but layers are not as easy to spot as patterns, and layers can change, whereas the pattern remains the same despite the layers changing due to different implementations.

You cannot compare those two words, because they describe different concepts.
To me, a layer is something opaque that offers some functions I can use to do things. For example, a good hardware layer for a wireless transmitter would just give me a send and a receive-function (based on bytes, for example), hiding all the ugly, ugly details from me.
A role is a way an object will behave. For example, a transformation in one of my compilers is going to take an abstract syntaxtree and return an abstract syntaxtree or an affection in my current project is going to take a state-difference and return a specifically altered state-difference.
However, coming with those two definitions, I do not see the need to chose a single "correct" term and burn the other as wrong, because they don't conflict much. A part of a layer has a certain role, and a set of objects conforming to certain roles form a layer. Certainly, the controller forms a certain layer between the UI and the model (at least for input), however, ot also has a role - it turns certain event into certain other events (and thus, it is some sort of adapter).

I think either can be reasonably argued for, but I think describing the parts as "layers" is more consistent with other conventions, like the OSI model. Since the View, Controller, and Model get progressively closer to your data, it's more of a layered structure. It seems that "roles" would apply to different parts of an application on the same layer.

Why not Both? I see it as 3 separate layers implementing 3 different roles.

It's all terminology, but I think the correct software architecture term would be "layer", as in logical layer. You could use the term "architectural layer" if it is clearer.
The thing is, it's just a different way of slicing an application: a classic n-layer app would be:
UI
Business Logic
Persistence
You could have the following logical layers in a simple MVC application:
UI
Controller
Model
Persistence
But you could still talk about the "UI" and "Controller" together as forming the User Interface layer -- I usually split out the Controller into a separate layer when describing and diagramming these architectures, though.

Related

When to use MVC and ECB?

According to the book I am reading, I understand this facts. Entity objects is like model objects in MVC which are responsible for maintaining data. Boundary objects are those which interact with external users, handling both input and output. In MVC, user input is detected by control objects, but the handling of output is the responsibility of view objects. That are the difference I have found. But when I do googling, many said that MVC is typically used in user interface design whereas ECB is most often used in business logic. What does that mean? MVC is just used for user interface? If so, what is the responsibility of the Controller and view object in MVC?
The two architectural patterns have a different origin:
MVC was born from the effort to decouple business logic from user interfaces, in the early days of GUIs. It separates components by purpose, and user-interface was a big one.
ECB comes from use-case driven development. It separates components based on the use-cases, and these typically capture user/business goals.
The two patterns have some similarities. Indeed, the BCE-Entity components have the same purpose than the MVC-Model components: managing the domain objects.
However there are subtil differences: the MVC-Controller is meant to capture all the user input, and the MVC-View the outputs. The BCE-Boundary is meant to cover the full user interface (input and output) and relate to the BCE-Controler, which coordinates the other BCE components for the purpose of a use-case/goal. In other words, the BCE-Controller is related to the business logic (i.e. the model in the MVC).
If the application covers only one use-case, the main difference will be the controller. But if an application covers several different use-cases, you'll end-up with a different architecture.
In practice, BCE did not really made it through in modern user interfaces, whereas MVC is still very popular thanks to some frameworks.

Fat models and skinny controllers sounds like creating God models

I've been reading a lot of blogs which advocate the fat models and skinny controllers approach, esp. the Rails camp. As a result the routers is basically just figuring out what method to call on what controller and all the controller method does is call the corresponding method on the model and then bring up the view. So I've two concerns here which I don't understand:
The controller and router are really not doing much different tasks other than just calling a method on the God-like model based on the route.
Models are doing too much. Sending emails, creating relationships, deleting and modifying other models, queuing tasks, etc. Basically now you have God-like objects that are supposed to do everything that may or may not concern with modeling and dealing with data.
Where do you draw the line? Isn't this just falling into the God pattern?
It might not be the best idea to look at Rails as a staple of MVC design pattern. Said framework was made with some inherent shortcomings (I kinda elaborated on it in a different post) and the community only just now has begun addressing the fallout. You could look at DataMapper2 development as the first major step.
Some theory
People giving that advice seem to be afflicted by a quite common misconception. So let me begin by clearing it up: Model, in modern MVC design pattern, is NOT a class or object. Model is a layer.
The core idea behind MVC pattern is Separation of Concerns and the first step in it is the division between presentation layer and model layers. Just like the presentation layer breaks down into controllers (instances, responsible for dealing with user input), views (instances, responsible for UI logic) and templates/layouts, so does the model layer.
The major parts that the model layer consists of are:
Domain Objects
Also known as domain entities, business objects, or model objects (I dislike that latter name because it just adds to the confusion). These structures are what people usually mistakenly call "models". They are responsible for containing business rules (all the math and validation for specific unit of domain logic).
Storage Abstractions:
Usually implemented using data mapper pattern (do not confuse with ORMs, which have abused this name). These instances usually are tasked with information storage-from and retrieval-into the domain objects. Each domain object can have several mappers, just like there are several forms of storage (DB, cache, session, cookies, /dev/null).
Services:
Structures responsible for application logic (that is, interaction between domain objects and interaction between domain objects and storage abstractions). They should act like the "interface" through which the presentation layer interacts with the model layer. This is usually what in Rails-like code ends up in the controllers.
There are also several structures that might be in the spaces between these groups: DAOs, units of work and repositories.
Oh ... and when we talk (in context of web) about a user that interacts with MVC application, it is not a human being. The "user" is actually your web browser.
So what about deities?
Instead of having some scary and monolithic model to work with, controllers should interact with services. You pass data from user input to a specific service (for example MailService or RecognitionService). This way the controller changes the state of model layer, but it is done by using a clear API and without messing with internal structures (which would cause a leaky abstraction).
Such changes can either cause some immediate reaction, or only affect the data that the view instance requests from model layer, or both.
Each service can interact with any number (though, it's usually only a handful) of domain object and storage abstractions. For example, the RecogitionService could not care less about storage abstractions for the articles.
Closing notes
This way you get an application that can be unit-tested at any level, has low coupling (if correctly implemented) and has clearly understandable architecture.
Though, keep in mind: MVC is not meant for small applications. If you are writing a guestbook page using MVC pattern, you are doing it wrong. This pattern is meant for enforcing law and order on large scale applications.
For people who are using PHP as primary language, this post might be relevant. It's a bit longer description of the model layer with a few snippets of code.
If the "model" classes are implemented poorly yes, your concern is relevant.
A model class shouldnt be doing Email (infrastructure tasks).
The real question is what does model in MVC imply.
It isnt restricted to POCO classes with a few methods.
Model in MVC means Data and Business logic. Treat it as a superset of classic core POCO models.
View ==== Controller ==== Model ---> Business Process layer --> Core models
Throw in Infrastructure assemblies and Data Access layers and use injection to hand that into the BPL then your a process is using MVC as intended.
BPL may invoke UoW / Respository patterns, and execute business rules and call Infrastructure features by way of injected Objects or interface patters.
So the recommendation to keep a controller skinny doesnt mean the "person" class in a classic Core model should have 50 methods, and call Email directly. You are right to think this is wrong.
The Controller May still be required to instantiate and inject Infrastructure classes into the BPL or core layer if called directly. There should be a business layer or at least classes orchestrating calls across Classic Object model classes.
Well thats my "view" anyway ;-)
For generic take on MVC the wiki description http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
A Little Blog that talks about the "M" in MVC. http://www.thedeveloperday.com/skinny-controllers/
I think you can make a distinction between a single fat model (possibly named App or Application), and several fat models broken down into logical groups (Business, Customer, Order, Message). The latter is how I structure my apps, and each model roughly corresponds to a database table in a relational database or collection in a document database. These models handle all aspects of creating, updating, and manipulating the data that makes up the model, whether it is talking to the database or calling an API. The controller is very thinm responsible for little mor that calling the appropriate model and selecting a template.

Difference between presentation layer and user-interface

What is the difference between a presentation layer and an user-interface?
They are close in execution, but they come from different directions. They aren't well defined, depending on the specific context, they may be almost identical or overlap only slightly.
Presentation layer is term in the taxonomy of code and associated resources.
User Interface is the implementation of the intended User Experience in terms of page layout, page transitions and page control elements. (I am using "page" loosely here - you can replace it with "form" or "window").
The distinction is important when you consider how a user interface gets created. If you come from the code, you are basically working with the needs and mechanisms of the code - what data is there to show?, and in what ways your code can change that?
If you come from the user, the questions are rather what data the does the user need? and what data the user wants to change?
(The first one isn't necessarily worse - it's perfect for users who have a good idea of the inner workings of the application, and it makes it often easier to make use of the full capabilities of the code.)
The link in the John's answer refers to the OSI model, which is not the term intended here IMHO.
I think presentation layer and UI are overlapping concepts, though not 100% overlapping.
Form one angle:
The term presentation layer suggests a layered structure in the application, while the term UI does not suggest anything about the inner structure of the application.
From another angle:
The term UI might only include the collection of controls and their event handlers, while the term presentation layer could include some deeper non visual parts of the application like ViewModels or Presenters.
The presentation layer delivers information to the application layer for display.
The presentation layer, in some cases, handles data translation to allow use on a particular system.
The user interface shows you the data once the presentation layer has done any translations it needs to.
More here: http://en.wikipedia.org/wiki/Presentation_Layer
Here's my own interpretation:
Presentation layer loosely refers to the layer which is responsible for somehow displaying the data for the users. It is often spoken of in the context of a software architecture along with other layers such persistence layer, business logic layer, etc, and rarely by itself.
User interface simply refers to the point of interfacing between the users and some software programs. User interface do not always have to have a nice graphical windows capabilities. A console program, one which runs on the prompt, is also said to have a user interface, just not a graphical one.

Model View Presenter (MVP) What is the model?

I just cannot seem to get my head around what exactly is the MODEL in MVP.
If I have a layered architecture PRESENTATION / APPLICATION / DOMAIN / INFRASTRUCTURE, what exactly is the MODEL?
DOMAIN objects accessed through
lower layers?
A separate object defined in the
PRESENTATION layer that maps to the
UI and uses data obtained from a
lower layer?
If someone could clear my understanding on what is the MODEL it would be greatly appreciated.
The Model is normally the group of classes/types/components that represent the core domain (business or otherwise) that your application operates within. These are the classes that perform the key logic required, often in the form of business rules, and also consume/manipulate data.
In your layered example, the Model would mostly be found in the Domain layer but could also be in the Application layer.
I think you're having difficulty understanding it because you are trying to combine two separate architectural patterns, or ways of looking at the application, being n-tier/n-layer versus MVP.
It's completely reasonable (and quite common) to use some sort of Model/View approach while at the same time applying layering in your application.
Maybe you should focus on them one at a time to start with and then overlay them when you are more familiar with both.
In any of the Model-View-* architectures, the Model is what describes the data in your application (and, if they fit the need, are passed in to the View for rendering).
If your application already has Domain objects, it very well may be the case that you could use them for your Model.
It doesn't matter what architectural guidelines you're following, M is always going to be the same thing. The Model is the piece that is specific to your domain. It's the part that really is what you're application is trying to do. The Model is supposed to represent your business domain. This goes for MVP, MVC, MVVM, etc.
If you were making a inventory system, then an Inventory class would most likely be in your Model, a Product would probably be there, an Order, you get the idea. These are the things that compose your domain logic.
The model is the data. This might just be data out of a database in DataSets, or it might be a complete domain model with objects representing your field of business.
The view is the UI, whether web pages or a Windows application or a mobile device application.
The presenter is the glue between the two and the brains of the whole outfit. Actions initiated by the view take place in the presenter. Generally in a WinForms application, for instance, a Button.Click event in my View simply calls a method on the Presenter, which then takes whatever action is necessary (and it may just be doing something back in the View).
The presenter holds a reference to the view (through an interface), and to the model. The view has a reference to the presenter (usually I strongly-type this, but it can be an interface as well). The model doesn't know about the presenter or the view.

In Domain-Driven Design, can you use your domain entities in your UI?

In many leading DDD projects, especially MVC style, I see the UI using display objects that mirror domain entities, rather than using those domain objects directly. This style is obviously for decoupling and separation of concerns, and I personally prefer this style.
But what I'm not sure of, is whether this a strict tenet of DDD, or whether this is more just different developers' interpretation of it.
Can you use your domain objects directly in the UI, and still be following the DDD methodology in that act?
Or is it a DDD best practice to always use display objects?
Note: While I mention MVC, I'm really interested in whether display objects must be used in almost all DDD compatible UI patterns in a DDD project.
I didn't really start to understand why or how you would decouple the domain model from presentation concerns until I started following the work of Greg Young and Udi Dahan (via Martin Fowler).
They have been teaching a principle known as Command and Query Responsibility Segregation (CQRS).
My interpretation of CQRS is that there are two sets of responsibilities that can pull a domain model in different directions, resulting in a model that does a mediocre job of both. The two responsibilities are commands (i.e. behavior that would cause a write to the database) and queries (i.e. reading from the database in order to fetch data for UI consumption). An example would be adding getters and setters to your entities to support databinding in the UI. If your model has getters and setters, it will probably do a poor job of modeling state changes that need to happen transactionally or encapsulating business logic. It will also have no way of modeling the business context of state changes (see Event Sourcing).
In DDD terms, you might say that the domain model and the presentation model are usually in separate Bounded Contexts.
The solution as prescribed by CQRS is to create one model for commands and another for queries. If your current model has methods for changing state (i.e. the behavior in the model), and getters that expose state to a UI for databinding, you would refactor these two responsibilities into separate models for commands and queries. The query model will not be mapped to your domain entities, but instead directly to the database. If your database doesn't capture derived state from your domain model, check out a pattern called Eager Read Derivation.
If your system is simply CRUD and has no behavior, try out a scaffolding system that can be automatically built off of your database schema, like ASP.NET Dynamic Data
If you're doing an MVC pattern, you need view objects; the DDD is just your model. That doesn't mean you must always use MVC; a DDD could be built, say, as a simulator, where all you look at is log messages emitted. But in MVC you really should have separate view objects.
Now, ask yourself why that would be? The answer is that the view can change, even though the business model doesn't. The DDD model should express, in the business's terms, what is essential to the business.
DDD is a way of thinking while designing a software that starts with modelling the domain. As the webpage puts it:
Domain-driven design is not a
technology or a methodology. It is a
way of thinking and a set of
priorities, aimed at accelerating
software projects that have to deal
with complicated domains.
One thing that follows naturally out of this design pattern is a layered architecture. As it is said in DDD Pattern Summaries
Partition a complex program into
LAYERS. Develop a design within each
LAYER that is cohesive and that
depends only on the layers below.
Follow standard architectural patterns
to provide loose coupling to the
layers above. Concentrate all the code
related to the domain model in one
layer and isolate it from the user
interface, application, and
infrastructure code. The domain
objects, free of the responsibility of
displaying themselves, storing
themselves, managing application
tasks, and so forth, can be focused on
expressing the domain model. This
allows a model to evolve to be rich
enough and clear enough to capture
essential business knowledge and put
it to work.
Whether you need to have display objects to do that? That is just one way of implementing this, but might not even be the best to provide loose coupling. As for an example: maybe the view layer is but a webbrowser and xlt files to visualize xml files emmitted by the business layer? If anybody has more fitting examples, please add them. My point is that DDD stresses a layered architecture, but does not limit this to one possible solution.
Within an MVC design you would typically have a mapping from Repository -> Domain Models and then from Domain Models -> View Models. The View Models often contain Domain Objects though.
The answer is quite straight :
The domain objects have domain oriented design and methods.
The view objects have view/control oriented design and methods.
If you can use your domain objects in the view, they are maybe not quite domain oriented.
Domain objects are really the internal logic inside your business logic layer. They shouldn't be directly exposed to your clients (UI layer). Instead, encapsulate the usage of your domain model into application services. The application services can utilize lightweight DTOs and/or command objects to pass data and intent between the client and the domain model.

Resources