Model View Presenter (MVP) What is the model? - model-view-controller

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.

Related

Cocoa MVC ≠ actual MVC?

Today I was getting some refresh about software design patterns.
In particular I was wondering about the difference between MVC and Three-tier-layer. Basically, from what I read on wikipedia and other sources, the main difference between the two is the components interaction:
A fundamental rule in a three tier architecture is the client tier
never communicates directly with the data tier;
whilst
...the MVC architecture is triangular: the view sends updates to
the controller, the controller updates the model, and the view gets
updated directly from the model
Now: if we take the apple docs regarding this matter we see this:
And they clearify that Views and Model shouldn't communicate directly:
view objects are typically decoupled from model objects in an MVC
application
and
When a model object changes (for example, new data is received over a
network connection), it notifies a controller object, which updates
the appropriate view objects
And so on.
So, what's the matter here? Is Cocoa adopting its own idea of an MVC, regardless of the common one? Or am I missing something in the common way of seeing an MVC architecture?
While it can be said that Cocoa's version of MVC is a sort of subset of the actual definition of MVC, they are not separate entities. The Cocoa version of MVC typically revolves around the use of a View (typically an NSWindow and/or an NSView), a controller (typically an NSWindowController), and a model layer (anything from a simple array to a Core Data stack). The separation of powers in this model is clear, but where in the 'tier' structure that Wiki defines should each of these belong?
I would argue that the Controller and the View are a part of the client layer. Not only is the controller responsible for the delegation between the model and the view, but it is responsible for responding to user events and determining the correct course of action to take during non-framework error handling. By taking this approach to MVC, you can now begin to see how Cocoa does, in fact, satisfy the broader definition of the pattern.
A fundamental rule in a three tier architecture is the client tier never communicates directly with the data tier;
This one's probably the hardest to reason about of the 3, and it involves delving into what "communication" actually means in the context of the pattern. When we say communication, what we mean is that the controller has no direct involvement in the actions taken by the model. That's not to say that the controller cannot order a change in the contents of the model, but rather that the controller does not have a hand in how the model updates itself. The controller acts as a director, not an implementer, which vastly simplifies the creation of a database layer, and is one of the reasons that Core Data and SQLite3 exist as external frameworks rather than as Foundation classes.
view objects are typically decoupled from model objects in an MVC application
That brings up one of the age-old taboos when programming with the pattern: making your views too smart. The controller provides a solid barrier between the model and view, such that the controller acts as a director and a filter for content from the model layer. Without any such barrer, say a tableview, would have to ensure that every cell had a copy of the data from the database, and that each cell knew when and how to update itself when a change is propagated in another cell. In Cocoa, this is where our NSWindowControllers come in. They manage the display of a root view and act as a barrier between some model and the content of the view it manages. Though, it is important to note that the controller objects in Cocoa are view-biased, mostly because it would be nearly impossible to provide a generic outlet to any kind of model layer without quite a bit of unnecessary glue.
When a model object changes (for example, new data is received over a network connection), it notifies a controller object, which updates the appropriate view objects.
That's the way it should be, for the reasons I've laid out above. But, to build on the networking example you've given, consider this:
Given an NSOperation that fetches data, and a controller that manages a tableview, you would probably not like the controller sticking its fat fingers into the operation, nor would you like the tableview to receive raw NSData and have to spend valuable rendering time processing the result and displaying it.
And so on. So, what's the matter here? Is Cocoa adopting its own idea of an MVC, regardless of the common one? Or am I missing something in the common way of seeing an MVC architecture?
I guess the conclusion I would draw from this is that your definition of the separation of powers in MVC and in how Cocoa does it is off. Cocoa is fairly rigid about adhering to the pattern, though there is an interesting contemporary movement within the Objective-C community towards MVVM.
You are correct the MVC practiced in most cocoa apps is not the MVC as it is defined in the text books. There are many variations of MVC employed by different frameworks. The MVC employed by tools with visual designers are heavily influenced by their visual designer implementation. With XCode you have story boards and nibs. The cocoa libraries and the way concerns are separated are influenced by this. If you want to take advantage of these tools, I would recommend understanding how concerns are separated by Xcode and work within this approach. Your code will coexist with it more smoothly. Apple documentation will help with this.
That being said, MVC is about separation of concerns. Separating concerns is hugely important in designing and maintaining software. Separating concerns properly can reduce dependency, reduce cyclomatic complexity, and make your code much more testable and maintainable. I think it is good that you are paying attention to this and whatever way you structure MVC should look to the reason why you are separating concerns as the guide to implementation.

Application Architechture MVC,MVVM etc

Architecture patterns like MVC,MVVM, MVP are only used in presentation tier?. Can we use in Business Logic layer or Data access layer? I previously thought that Presentation Tier is View;BusinessLogic Tier is Controller/Viewmodel and Data Access Layer is Model. please someone clarify this..
The patterns you mention provide concepts to couple business and presentation tier. Considering a classical three tier architecture with the tiers you've mentioned: Data Access Layer, Business Logic, Presentation Layer, then MVVM, MVC, MVP provide concepts for the coupling of Presentation Tier and Business Logic. As the main idea is a loose coupling between the two to avoid logical dependencies between the two layers as much as possible, I would think of them as a kind of mediator (in the meaning of the word, not the pattern) or glue between them.
Let me clarify this for MVVM, exemplary:
You can write a complete presentation tier in WPF without utilizing MVVM. Just as well you can write the business logic without knowing the concept of MVVM. You don't need ViewModels at all to build a working application.
But: You have no chance to cleanly separate the concerns of presentation/UI and the actual logic which performs the tasks your software has been written for. The border between the two is kind of fuzzy in the real world: You calculate data, now you want to transform the data to display it in a diagram. Is this business logic? Yes and no. Is this UI logic? Yes and no. There's a grey zone: Kind of logic, kind of UI. This is where MVVM (and the like) kick in: You add a layer between business and presentation which is dedicated to this grey zone only.
For MVVM: The View is the View, it's the presentation layer. And the ViewModel is the grey zone, which is neither real Presentation, nor real business logic, but the glue between them. The Model is the model, it's the business logic. It could even be written without knowing that it will be used in a WPF application (theoretically). And there can be business logic, which is not even a model in the MVVM meaning, because it is not UI related at all.
Below this, comes everything else with the DAL at the bottom. The DAL should really not care about how business logic and presentation are glued together and is beyond the scope of the discussed patterns.
Architecturally, I would say that MVC, MVP and MVVM is the presentation tier. The point of view between each components are:
View
This is very clear that it belongs to presentation layer. Not discussion about this
Controller / Presentation / View Model
If you take off the N-Tier principal, this is the business tier. Seems like this design pattern were invented without taking any coupling with the N-Tier.
Controller has Session and HttpContext utilization. It is web dependent. According to N-Tier principal, the BLL must not know any UI. Therefore it goes for presentation tier.
Presentation has events / event handlers / delegations and some UI-specific data. (CMIIW, I'm not too fluent with MVP). Therefore it goes for presentation tier.
As other said, ViewModel is rather hard to be classified as presentation tier. However, I find it better to put into presentation tier. In my experience using WPF, sometimes I need to use MVVM specific objects like ObservableCollection and INotifyPropertyChanged and ICommand to force data binding refresh. Sometimes it is needed for the ViewModel to access custom session state, such as login, etc. Other times, you need to specify some UI-specific parameter such as font color, etc. This may be avoided by handling the logic in View, however I find it is easier to do it in ViewModel.
Another thing to consider, using MVVM prevent me to use Service - Repository pattern.
Model
If you take the N-Tier off from MV- pattern, this is the entity model. It is described at Asp.Net MVC, where the model will be used in the view, as the container for data. However, if you take N-Tier into account, then this is the business tier, where you do insert/update/delete operation to the data, and the logic for it resides.

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.

Does the MVC pattern describe Roles or Layers?

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.

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