What should own the model in an MVC pattern? - ios

Let's say that I'm drawing a solar system inside of a single SolarSystemView (a subclass of UIView). Should my SolarSystemView have an instance variable of class SolarSystem (a class containing a data structure with all of the important planetary and stelar properties), or should that be under ownership of an instance of a SolarSystemViewController? Or is it something completely different? I can't find any example code that gives a satisfactory answer.
I imagine that if the view owned the model, operations would be very smooth, but that also doesn't feel like good style. After all, the SolarSystem instance has to change dynamically somehow, and with the same or similar rate that the SolarSystemView updates.

In the MVC paradigm, the Model is supposed to be separated from the View. To get the data it needs to draw itself, it asks the Controller for it, which in turn asks the Model for it. That way, we decouple the information from the GUI. Think of it as Model Controller View if it helps. Therefore, in most cases, the Controller "owns" the Model.
For example, in cs193p, the CalculatorViewController (Controller) has a CalculatorBrain (Model) property, which it interacts with to get the results of equations to display in the View.
In your particular example, the SolarSystemViewController would probably have a strong reference to the SolarSystem, which it would poll for data that it would hand off the the SolarSystemView so that it could draw itself when it needed updating. The SolarSystemView might also notify the SolarSystemViewController when the user interacts with it so that it can display other views or update the SolarSystem, among any other tasks it could perform.
Note that the MVC paradigm in Cocoa and Cocoa Touch is a little different than the more generalized version of MVC seen elsewere, like Smalltalk. For example, if you look at the Wikipedia page on MVC the diagram there should look different than what you've been learning. In fact, GoF (Design Patterns) describes MVC thusly.
MVC consists of three kinds of objects. The Model is the application
object, the View is its screen presentation, and the Controller
defines the way the user interface reacts to user input. Before MVC,
user interface designs tended to lump these objects together. MVC
decouples them to increase flexibility and reuse. MVC decouples views
and models by establishing a subscribe/notify protocol between them. A
view must ensure that its appearance reflects the state of the model.
Whenever the model's data changes, the model notifies views that
depend on it. In response, each view gets an opportunity to update
itself. This approach lets you attach multiple views to a model to
provide different presentations. You can also create new views for a
model without rewriting it.
In both these cases, the Model itself is contacting the View to update it. However, on iOS, interaction between the Model and the View are handled through the Controller. This is well explained in the first session of cs193p as well as Apple's own documentation on MVC relationships. That way, you only need to rewrite the Controller code to reuse the Models and Views elsewhere.
Here's the MVC diagram from cs193p to clarify.

In this case, SolarSystemView should not contain any instant of the SolarSystem class. The SolarSystemViewController should be the go between your view (SolarSystemView) and the model (SolarSystem).

Related

Why does the View know about the Model?

I have done some work on ASP.NET MVC 3 but I'm no expert.
So, based on the pattern definition, the view has no direct awareness of the model and does not communicate with the model directly; only controller is directly dealing with model.
However, in ASP.NET MVC 3, I can access the model data directly from the view using Razor engine. Isn't that breaking the pattern design or am I missing something?
the view has no direct awareness of the model and do not communicate with the model directly
Not exactly. Exactly how to interpret this statement might depend on the reader.
I've read quite a bit on model-view-controller and asp.net-mvc and I find similar statements scattered around and so the way it's worded can be a bit confusing.
A view knows what the model is. That is, it should know what the model type is, what the model contains or by some means know how to use the model to display what is necessary.
If we have a page called UserProfile then the view knows that it should display the user's name, email address, age and favourite website.
The view might be told to expect a UserProfileViewModel. Such a class would contain exactly the properties that the view needs so that it can easily display them.
What is better to say is that the view should not modify the model. In fact, the view should not do much of anything. Views are supposed to be stupid - they aren't for processing business rules, modifying data, connecting to databases, and so on. They just display stuff.
The model contains the data, the controller manipulates the data and the view displays the data (model). The view therefore is the interaction with the user.
The view must know what to show, so it has the model (with its data) to do so. It never manipulates directly, but sends information to the controller which in turn will manipulate the data.
I guess you have mistaken the concept of MVC. MVC does not say that "View is not aware of Model". In practice, each view is tightly coupled with a model (unless view is coupled to dynamic model or base type).
MVC is actually separation of concerns.
Controller decides the business rule and decides what data to be shown to user.
Then it populates the Model.
Then pass on the Model to View. (Think of it like passing on some data to be displayed on view).
Now View is not aware how model is created and validation rules of model.
Model is not aware which view will consume it. There can be many views coupled to a model.
Controller is not aware of model validation or what property of model is being displayed on view.
And MVC is just a pattern to follow, it does not stop you from writing business logic inside view or make db calls from view.
Refer to this article to read about the three different types of "models" introduced by ASP.NET MVC.
What it sounds like you are referring to is the view model. This model is simply a container or a way provide structure around the data that the view is responsible for displaying. It is simply a data-transfer object (does not have any behavior).

Having MVC controllers light and models heavy

I have heard that the controller should be kept light and models heavy.
I am somewhat confused about the best practice on what should be kept in the controller and what should be kept in the model.
In our organization, we use Entity Framework where and put the tables there.
For the controller, we use LINQ and then send the info over to the view.
Kind of confused on what code should be in the Controller and in the Model.
DisclaimerThe whole topic is a giant mess. Especially when it comes to Web MVC. For all practical purposes it is impossible to use classical MVC pattern for web, because the view should be observing model. Theoretically you could implement something like that with WebSockets, but keeping a persistent model for each user is not a realistic solution.
Here is what you must know about MVC
The most important idea in both classical MVC and MVC-inspired patterns Separation of Concerns. It divides the application in two major layers:
Presentation layer
Governs the user interface. It deals with both creation of the interface and reacts to the user's manipulation of this interface. This interface might be GUI for a desktop application or HTML web page, but it also can be REST API or receiver-responder on a Mars rover. This is why a web application can implement MVC pattern in both frontend and backend.
The mandatory parts are views and controllers, but, in context of web, fully realized views usually also use multiple templates to create the interface.
Model layer
This is where all the business rules and logic lives. The M in MVC is not a single entity. Instead it is a layer, which contains different structures. Some of those structures are also responsible for interaction with storage.
What are the responsibilities of controllers ?
Controllers are part of presentation layer, which deals with user input. In context of web-based implementations, you will usually have 1:1 relationship between views and controllers, where controller receives the requests from browser and, based on the content of said requests, alters the state of model layer and view.
If you are using classical MVC or Model2 MVC, then that is the extent of controllers responsibilities.
In MVP and MVVM patterns, where you have a passive view, controller-like structures are responsible for acquiring information from model layer and passing it on to the current view instance. This post might provide some additional details on the MVC-inspired patterns.
But the controller is in no way responsible for any form of business logic. If it was, it would mean, that you have a leaking abstraction, because the structures of presentation layer would be doing work, which should be in the model layer.
Usually the controllers will the be simplest structures in you application.
What about the model ?
As mentioned before, model is a layer, which encompasses all of the domain business logic and related functionality. This layer , just like presentation layer, is made up from multiple groups of structures:
Domain Objects[1]
These structures are usually what people mean, when talking about "models". They are also known as model objects or business objects. This is where most of domain business logic ends up.
Data Storage Structures
This group would contain all of the classes, which abstract the interaction with storage (SQL databases, caching systems, noSQL, remote SOAP or REST APIs). They will usually implement some variation of data mapper or repository pattern , but you could be using some other solutions too, like unit of work. The implementation details are not so important. What is important is that they let you store data from and retrieve information into your domain objects.
Services
Or you could call the "components". There are high level abstractions in your model layer, which facilitate the interaction between domain objects and storage structures. The usually represent large chunks of model layer, like "recognition service", "mailers", "article management", and will provide the interface for presentation layer to interact with.
That's something of a religious debate.
Some like as little as possible code in their controller and other as little as possible in their model.
Do what feels natural to you in the project, but be consistent within it.
All else is dogma you can pick an example either way and make a case.
Model is the core of your application. It is best to think of models as of your business entities. Do you want to create a view of an invoice? Then Invoice be your model, it represents the underlying object.
Controller is just a way to handle requests from a client, retrieving the data from database (or updating them) and flushing out the responses.
Your thoughts about the application design should be model-centric, that's the important part.
In simple terms, Model represents the underlying data that your application will be using. It is to be designed in a way that it can be used across different applications.
For example, A model to represent News data can be used by console commands, Web service etc.
It is in model where you will have ur business logic defined, independent of the view.
Controller can be thought of as glue that binds Model and View together. They deal directly with client requests and accordingly interact with views and models.
In a well designed application, you data structure and business logic will be designed in a
Model, making it "heavy". While Controller will just interlink your model and view with the client requests, making it "light".
In the classic Model-View-Controller MVC pattern, your Model is essentially a "headless" application, with no UI and is completely UI-agnostics. It offers an API that is the functional core of the application.
The View is the user interface, however you choose to define it (web page? elevator control panel? something else?). A given application might have 1 view or it might have many views.
The Controller (or Controllers — like Views, you might have one to many Controllers for a given application) relays and transforms events, notifications and data between View and Model so as to preclude the Model from needing to know anything that is View-specific.
The idea is to isolate the core application (the Model) from the user interface (the View). From that some things follow:
The View is aware of and communicates with both Controller and Model (you're unlikely to try to wire up the View to another Model) and expected for the Controller to be aware of both View and Model.
The Controller is aware of and communicates with both View and Model.
The Model knows nothing of Controller or View.
Code that performs business logic should be in the Model, not in the Controller.
I'm no MVC expert, but try and concentrate on the fact that the controller should use the input from the user to direct them to the correct view.
I don't know if NerdDinner is an ideal example, but you can see Scott Hanselman et al does a little bit of data access from his EF context but pushes most of the other logic to service classes or helpers on the model.
I don't know if I agree with the 'models heavy' part, as I don't use the models as 'business objects'. If I really need a lot of 'business' logic, I will typically create that in a separate 'Domain' layer and may even have a separate Data Access layer on top of this. But for a lot of simple (see: non-enterprise) projects, this is overkill in my experience.

what's the most appropriate pattern to get and set core data model from multiple view controllers?

Say I have a core data model with a few entities and, throughout the application's lifecycle, I'll be getting and setting properties of these entities from different views.
At least to me, it seems like passing the managed object context around from view controller to view controller and having the controller's code know about the different entities or derived objects goes against decoupling. As a matter of fact, there is a similar question where the only answer suggests passing around the managed object context.
So, in the spirit of MVC, I thought it might make more sense for view controllers to stick to controlling views, and have a singleton model controller through which these view controllers can query the model to feed their views and notify back when the model needs to be updated based on user interaction with the view.
But I'm not sure how to go about implementing the single model controller interface. For instance, here's a few ideas:
make this controller both a delegate and data source to all view controllers?
have the controller be only a data source and use notifications for updates?
kvc/o?
is the whole idea of a centralized bridge from/to the model just overengineering the MVC pattern? That is, is there some reasonable argument in favor of instead passing the managed context around and this not being considered crappy object-oriented design?
Another thing I'm thinking is, if the singleton controller is a delegate and data source, the methods to get model data and update the model should implement some sort of visitor pattern, right? Meaning, for example, if view controller A allows the user to interact with model entity / object A and some view controller B allows for the same for a model object B, and both view controllers rely on the same delegate, the delegate will have to have some way to know which model entity it should target depending on what concrete controller is calling on it.
I'd appreciate any thoughts / ideas
Your idea of a "model controller" makes sense, the problem is I think you may be thinking of it wrong.
It's not really a "model controller," it is the model. In MVC (traditionally), the views communicate with their controller for advice on what to do with interactions, and the controller decides what to tell them based on its logic and information it gathers from the model.
So really, you're simply abstracting the model further, which is a good thing. The idea of a "centralized bridge" is what you want in MVC. Your controller should see a high-level abstraction of the underlying model's implementation, as with all interfaces and layers of abstraction.
As far as implementing the model goes, I'm not sure which is the "best" way to do it, but I can't imagine using the delegate/data source strategy (or sending notifications to the controller) would be detrimental, I'd guess it depends on what you're comfortable with. If you love KVC/KVO, I doubt it'll hurt you. As far as the visitor pattern goes, the logic concerning keeping track of which controller gets which object should be within the model.
It seems to me that your biggest concern is with passing the model around from controllers. It is perfectly alright for the controllers to reference and use the model, but trying to manage their creation and penetration, you're right, is a bit much.
I'd recommend using a Dependency Injection container that can generate the access layer to your model. This way the controllers will get the model passed to them via DI, w/o having to pass around how to create the model classes.
The idea of a single centralized bridge isn't a bad one either, but it would make things a little tricky to unit test.
In the end, I ended up dropping the delegate / datasource approach for a singleton pattern:
I figured the following:
all controllers are collaborating with a single shared
managedObjectContext
the Core Data model itself revolves around a single "configuration"
entity (not the configurations that the Core Data literature refers
to).
This "default configuration" is also what all controllers interact
with, since all other entities exist in the context of this
configuration entity.
So essentially, I have a shared resource which should be accessible in a way similar to a global variable.
So I encapsulated the shared resource in a Singleton through whose interface all other controllers can query and modify the model without knowing much about the internals.
The general interface allows for things like:
[ModelControllerBridge sharedBridge] defaultConfiguration] which
returns the default shared NSManagedObject
[[ModelControllerBridge sharedBridge] newDataSample] which returns a
new NSManagedObject and internally allocates and inserts it in the
appropriate entity within the model.
[[ModelControllerBridge] shouldCommitChangesToModel] which signals
the context should be committed to the permanent store
etc.

Is there any dependency between view and a model?

Normally in the MVC Pattern, when a user clicks on a page the request would be sent ,then controller would handle the request ,then process it using the model and route it to the appropriate view.
I have read the post about the passive model and active model,but is there a possibility where the view directly interacts with the model, would that be a bi-directional relationship (i.e Model<->View) or one-directional (i.e Model->View).
Is it appropriate to have a relationship between Model and View? Well in a ASP.NET MVC project should i have a relationship between model and view, or have it independent of the model?
I think it's almost always preferable to have your views be model-specific, that is, strongly-typed. Where models share related data, you can reuse partial views that are specific to that subset of data. In ASP.NET MVC, your model is -- or should be -- ignorant of the view since they only way they can interact is through a web request, which is a controller function. No you may say that you could interact through web services, but I would consider those to just be another flavor of controller. In fact, with MVC, I see very little need to develop a separate web service at all, using REST-based controller actions instead.
I always see the View as the way to present the Model. According to this point of view, the View is Model aware and in ASP.NET MVC you should inherit pages from ViewPage to avoid abusing from ViewData or castings.
With that in mind, the Model is not view aware and is just an object that is used from the view to present data to the user.
Finally, you can share the same Model from different Views, for example an XML output can share the same model as the HTML output but the views can be very different.
The cycle is more or less, Controller generates Model, passes it to the View, that shows de Model and in case there's interaction, posts the input to the Controller and the cycle starts again.
In Java Swing MVC is implemented as the View and Controller combined, with a View that both reads from the model and registers for events from it which effectively makes them loosely dependent on each other.
Usually web applications don't do this as the real view is rendered on the client and can't receive events from the model as easily, so in those cases the relationship only goes one way. Its certainly not a bad thing to have a relationship between the model and the view as long as the Model does not dependent directly on and view classes. In that case a dependency cycle would be set up and that harms maintenance and especially testing.
For example the way this is achieved in Swing is via a Listener interface, which the view can then implement/provide an implementation of to the model.

What's the difference between a ViewModel and Controller?

What are the responsibilities of one vs the other?
What kind of logic should go in one vs the other?
Which one hits services and databases?
How do I decide if my code should go in the viewmodel or the controller?
For the record, I am using ASP MVC, but since the question is architectural, I do not believe it matters what language or framework I am using. I'm inviting all MVC to respond
The ViewModel is a Pattern used to handle the presentation logic and state of the View and the controller is one of the fundamentals parts of any MVC framework, it responds to any http request and orchestrates all the subsequent actions until the http response.
The ViewModel Pattern: More info
In the ViewModel pattern, the UI and
any UI logic are encapsulated in a
View. The View observes a ViewModel
which encapsulates presentation logic
and state. The ViewModel in turn
interacts with the Model and acts as
an intermediary between it and the
View.
View <-> ViewModel <-> Model
The Controllers (Comes from the Front Controller Pattern): More Info
It "provides a centralized entry point
for handling requests."
HTTP Request -> Controller -> (Model,View)
--Plain Differences:--
While the ViewModel is an optional
pattern the Controller is a must, if
you are going the MVC way.
The ViewModel encapsulates
presentation logic and state, The
Controller orchestrates all the
Application Flow.
The ViewModel can be on the client side as well as server side.
Wherever it may be, the sole purpose of viewmodel is to play the
presentation data.
In MVC architecture Viewmodel is not mandatory but with out controller the request from the client cannot be processed.
Controller can be visualised as the main interface between client and server to get any response from the server. It processes the client request, fetches data from repository and then prepares the view data. Viewmodel can be visualised as view data processor/presenter thus an interface to manage the view more eloquently.
In the overall context of a web application we can say the controller is the application request handler whereas viewmodel is only the UI handler.
The Model-View-Controller (MVC) is an architectural design pattern which exists, primarily, to separate business logic from the presentation. Basically, you don't want your back-end touching your front. It typically looks like this:
The reasons for doing this is because, by separating the back-end and the front, you don't tie your user-interface directly to your data/work. This allows you to put new interfaces onto your business logic without affecting said logic. In addition, it also improves the ease of testing.
A simple example of where MVC comes in handy - let's say you have an application that manages your company's finances. Now, if you are correctly using MVC, you can have a front end that sits at some financier's desk and lets him handle transactions, manage the finances, etc. BUT, because the business logic is separate, you can also provide a front-end to your CEO's Blackberry that lets him see the current status of the business. Because the two front-ends are different, they can do different things while still providing (different types of) access to the data.
EDIT:
Since you updated your question a bit, I'll update my answer. There is no perfect science to the separation of MVC. There are some good rules of thumb, however. For example, if you are talking about GUI components, that is probably a view. (Are you talking about look and feel, usability, etc.) If you are talking about data and the "business" side of the house (databases, logic, etc), you are probably referring to a model. And, anything that controls the interaction between the two is most likely a controller.
In addition, it should be noted that, while Views and Models are typically "physically" separated, a controller can exist with a view when it makes sense.
You are correct when you say the framework (or even language) for MVC doesn't matter. The pattern itself is language agnostic and really describes a way to architect your system.
Hope that helps!
I think there's some value to learning received doctrine. But there is also value in understanding how the doctrine came to be the way it is.
Trygve Reenskaug is widely credited with inventing MVC. N. Alex Rupp's article Beyond MVC: A new look at the servelet architecture includes a History of MVC. In a section on Reenskaug's 1978 work at Xerox Palo Alto Research Center, there's a link to his paper Thing-Model-View-Editor: an Example from a planningsystem. There the pieces are described like this.
Thing
Something that is of interest to the user. It could be concrete, like a house or an integrated
circuit. It could be abstract, like a new idea or opinions about a paper. It could be a whole,
like a computer, or a part, like a circuit element.
Model
A Model is an active representation of an abstraction in the form of data in a computing
system
View
To any given Model there is attached one or more Views, each View being capable of
showing one or more pictorial representations of the Model on the screen and on hardcopy. A
View is also able to perform such operations upon the Model that is reasonabely associated
with that View.
Editor
An Editor is an interface between a user and one or more views. It provides the user with a suitable command system, for example in the form of menus that may change dynamically
according to the current context. It provides the Views with the necessary coordination and
command messages.
Rupp identifies Reenskaug's Editor as a Controller or Tool.
MVC Triads emerged in SmallTalk-80. The model was an abstraction of the real-world concept, the view was its visual representation, and the controller was the buttons and slider bars that allowed the user to interact with it (thereby "controlling" the view). All pieces in the triad were interconnected and could communicate with the other two pieces, so there was no layering or abstraction involved. Since then, Reenskaug has "preferred to use the term Tool rather then Controller." According to his notes, these are the terms he has used in later implementations
Some logic and model should be invoked to generate some data (structured or semi-structured). From this data the returned page/JSON/etc. is created, typically with only rudimentary outlining logic.
The first part (creating the data) is done by the controller (via the model usually). The second part - by the View. The ViewModel is the data structure being passed between controller and view, and usually contains only accessors.
Model represents your data and how it's manipulated. Thus, model touches the DB.
View is your UI.
Controler is the glue between them.
MVC stands for Model, View, Controller.
Model = Data (Database tables)
View = HTML, CSS, JavaScript, etc
Controller = Main logic, a contract between Model & View.
In simple and graspable terms,
MVC allows you to develop your applications in a way that your business data and presentation data are separated. With this, a developer and designer can work independently on a MVC app without their work clashing. MVC makes your app avail OOP too.

Resources