MVC: why the separation of model, view, and controller? - model-view-controller

Other than the “philosophical” aspects of it, is it a bad idea to have my controller also be my model?
It seems to save some programming time. I don’t have to create logic between the controller and the model, since it’s the same thing. And I can directly interact with the view.
What’s the point of separating the M and the C? Is modularity — that is, the ability to swap one model and controller set for another — the only reason to separate them? It seems to me that “swapping” modules out happens a lot less than (for example) having to update both the model and the controller because something in the model is changing.
It seems odd that a simple calculator, according to the MVC concept, should have both a controller and a view for its settings (like default settings, or something). I know this is a simple example, but it seems to apply to all cases (except maybe frameworks).

The primary reason is for reusability of code. If you’re only ever going to write one program in your professional life, then perhaps it doesn’t matter. If you plan to make a career of it, having reusable pieces is valuable. Well-designed model, controller and view classes are very easy to drop into other programs. I do this all the time.
Consider UITableViewController, which is a Controller. Now imagine if it were designed exclusively to handle music tracks (the Model), and you needed to create a completely different table-management class when you wanted to handle something else. Avoiding this nightmare is why MVC is heavily used in Cocoa.
There are other ways to split things up. Some languages subclass heavily rather than delegating. But in Cocoa, the primary means of splitting up programs is MVC, and it works very well.
EDIT: Just some more reasons from the world of developing commercial apps.
Memory handling is much easier in MVC. You can hold on to your model objects and throw away your view objects (and many of your controller objects) when they go offscreen.
It’s easier to serialize model objects that aren’t wrapped up with controllers and views, and it’s much easier to display the same data in multiple ways. Even in a “simple” text editor, you may want to be able to do split-screen, or have multiple windows showing the same document. In MVC that’s very easy.
If you need no flexibility now or in the future, you don’t need much architecture. But most real projects aren’t so simple. MVC grew out of Xerox’s experience with writing large programs and the difficulties encountered when everything was thrown together.
EDIT 2: I was looking at your earlier edit: “It seems odd that a simple calculator, according to the MVC concept, should have both a controller and a view for its settings (like default settings, or something).”
This is exactly the reason for MVC. It would seem crazy to have to re-code all of the things required for saving user settings specially for a Calculator app. You’d want a generic “please save these user settings” that was completely separate from the UI and that you could reuse. On OS X it’s called NSUserDefaults, and the Calculator app stores its configuration in exactly this way.

MVC is a standard pattern that is well understood in the development community, and for good reasons. The separation really makes things easy to read, easy to troubleshoot, easy to find, and easy to test, as individual components, each with its own area of responsibility.
Do you have to use it? of course not. But keeping the parts separate is generally considered a good idea.

The controller knows how to link a specific view to your model. The separation of model and controller, apart from improving documentation and maintainability, has the immediate benefit of allowing multiple views to display the same information from the model without adding any complexity to either.
That applies not just to multiple views in the same application, but also to the multiple variations in views you'll have across multiple versions of your application. Your model is insulated and logically clean.
Combining model and controller is a classic false economy in my opinion. It may feel like it saves a few minutes, but it costs significantly as an application develops and grows.

If it works for you then it works. Period. The reason for separation of Models, Views, and Controllers revolves around the idea that most development for enterprise applications is done by a team of developers.
Imagine 10 developers trying to work on your controller. But all they want to do is add something to the model. Now your Controller broke? What did they do?

The Models are usually separate components which can be re-used between Controllers. If you are absolutely certain you won't be re-using Models in multiple Controller, I don't really see a problem with blending these concerns.
I guess one could argue why even use MVC design if you are planning on deviating. Maybe there is a more suitable pattern to follow for your situation. Can you give us an example of something you've done where the Controller is the Model? It would help us understand what you are trying to do better.

MVC is all about management (separation of data, representation and business logic). So it's like this: if you run a small company, having a MS-sized management would be a real drag. But if you are a giant corporation, not having big middle management is impossible.
Honestly, in most of my college progamming assignments, I combined the models and controllers, because I didn't see the need for the separation. But working on big projects? The deficiency would be pretty obvious if you try to not separate. Just do what you feel right.

The model depends on neither the view nor the controller. This is one the key benefits of the separation. This separation allows the model to be built and tested independent of the visual presentation.

Related

Pros/cons of view being responsible for reading/writing data

I have a view that I may use in any number of applications. It's a special viewer for a kind of data type. It contains a special reader for files that pertain to this data type and it can write them. What are the pros and cons of doing it this way? In a recent project, the MVVM proponents argued the view must be "dumb". This makes no sense because how can it be dumb if it is a narrowly specialized viewer? Is it possible that MVVM comes from the web world where viewers are simple? Anyway, the MVVM proponents also believed any data that goes into a view must be conditioned first e.g. converted to HTML, if the view is a webview. Seems like overkill. Why do that?
The concept of MVVM is to separate business logic (model) from view. In your case the reader writer should be in the model code. The Pro is that if you at any point want to make changes to the view side you can do so without changing or moving around code that does the actual data exchange (read write).
It also means that you can write tests against your model and if you change your view the model and test code will be left untouched.
Con with MVVM is that it adds some extra layer of code, it can add some development time (at least when one is new to MVVM) and in the beginning one may feel a bit locked by follow a pattern.
In the end I usually find the Pros to be bigger. One get a good and well thought through Design, separation of concerns for the codebase, easy to test different parts and the day you get a request for modifying or extending the control it will be much easier.

Is it good to develop view before model (in MVC pattern)?

I was wondering about the best practice when using the MVC pattern.
When you develop an app for a client, you want to think business. You want to think as the customer would. That's why I'm wondering :
Isn't it better to develop the view part, without any data treatment, so the customer can validate it ?
I see this practice as powerful as TDD is, I mean if you clearly know what your program will look like, you know which treatment it will require, making the model part a bit more concrete and business oriented, instead of making it too abstract and global.
I can not see downsides to this, so if you can see some, or explain me why it's not a good idea, please do.
Thanks :-)
The main benefit, as I see it, would be the ability to provide the client with hands-on prototype.
It not uncommon for clients to change their mind, because often, when they hire a developer or company, they actually have only a vague goal for the end product. This way you would mitigate the risk of large scale changes late in the projects life-cycle.
As for implementation of such approach, I would recommend for you to look into concept of "presentation objects" (Fowler has this annoying habit of slapping "model" on every damned term).
With presentation objects you would gain an ability to "shim" the data from model layer's services. And it also would let you figure out, what exactly services (and service calls) will you *UI layer( interact with).
Note: of course I am assuming that with "MVC" you do not mean some Rails-style abomination, where "views" are just dumb templates.

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.

What do you call a generalized (non-GUI-related) "Model-View-Controller" architecture?

I am currently refactoring code that coordinates multiple hardware components for data acquisition, and feeling a bit like I'm recreating the wheel. In particular, an MVC-like pattern seems to be emerging. Except, this has nothing to do with a GUI and I'm worried that I'm forcing this particular pattern where another might be more appropriate. Here's my scenario:
Individual hardware "component" classes obey interface contracts for each hardware type. Previously, component instances were orchestrated by a single monolithic InstrumentController class, which relied heavily on configuration + branching logic for executing a specific acquisition sequence. After an iteration, I have a separate controller for each component, with these controllers all managed by a small InstrumentControllerBase (or its derivatives). The composite system will receive "input" either programmatically or via inter-hardware component triggering - in either case these interactions are routed to, and handled by, the appropriate controller.
So, I have something that feels MVC-esque, but I don't know if that's because I'm forcing the point. With little direct MVC experience in application development, it's hard to know if I'm just trying to make my scenario fit MVC, where another pattern might be a good alternative or complimentary. My problem is, search results and wiki documentation of these family of patterns seems to immediately drop me into GUI-specific discussions.
I understand "M means Model data and the V means View" - but what do you call the superset pattern? Component-Commander-Controller?
Whence can I exhume examples exemplary?
IMO a "view" is not necessarily a GUI component. The pattern is easiest to demonstrate with GUIs but that does not limit its usability to GUIs. If it works for you, don't worry about the name :-) And of course, feel free to tailor it according to your needs.
Update: Of more generic kins of MVC, the only example which surfaced in my mind (after a day's background processing) is PAC.

What is MVC and what are the advantages of it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I found What are mvp and mvc and what is the difference but it didn't really answer this question.
I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked easy and separated process from display, are there advantages besides this that we don't know about and could be missing out on?
Pros
Display and Processing are seperated
Cons
None so far
MVC is the separation of model, view and controller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class.
For example, while a table grid view should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the model) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the controller.
A 'save file' dialog (view) ultimately passes the path, once picked by the user, on to the controller, which then asks the model for the data, and does the actual saving.
This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each.
Separation of concerns is the biggy.
Being able to tease these components apart makes the code easier to re-use and independently test. If you don't actually know what MVC is, be careful about trying to understand people's opinions as there is still some contention about what the "Model" is (whether it is the business objects/DataSets/DataTables or if it represents the underlying service layer).
I've seen all sorts of implementations that call themselves MVC but aren't exactly and as the comments in Jeff's article show MVC is a contentious point that I don't think developers will ever fully agree upon.
A good round up of all of the different MVC types is available here.
Jeff has a post about it, otherwise I found some useful documents on Apple's website, in Cocoa tutorials (this one for example).
I think another benefit of using the MVC pattern is that it opens up the doors to other approaches to the design, such as MVP/Presenter first and the many other MV* patterns.
Without this fundamental segregation of the design "components" the adoption of these techniques would be much more difficult.
I think it helps to make your code even more interface-based.. Not only within the individual project, but you can almost start to develop common "views" which mean you can template lot more of the "grunt" code used in your applications. For example, a very abstract "data view" which simply takes a bunch of data and throws it to a common grid layout.
Edit:
If I remember correctly, this is a pretty good podcast on MV* patterns (listened to it a while ago!)
MVC is just a general design pattern that, in the context of lean web app development, makes it easy for the developer to keep the HTML markup in an app’s presentation layer (the view) separate from the methods that receive and handle client requests (the controllers) and the data representations that are returned within the view (the models). It’s all about separation of concerns, that is, keeping code that serves one functional purpose (e.g. handling client requests) sequestered from code that serves an entirely different functional purpose (e.g. representing data).
It’s the same principle for why anybody who’s spent more than 5 min trying to build a website can appreciate the need to keep your HTML markup, JavaScript, and CSS in separate files: If you just dump all of your code into a single file, you end up with spaghetti that’s virtually un-editable later on.
Since you asked for possible "cons": I’m no authority on software architecture design, but based on my experience developing in MVC, I think it’s also important to point out that following a strict, no-frills MVC design pattern is most useful for 1) lightweight web apps, or 2) as the UI layer of a larger enterprise app. I’m surprised this specification isn’t talked about more, because MVC contains no explicit definitions for your business logic, domain models, or really anything in the data access layer of your app. When I started developing in ASP.NET MVC (i.e. before I knew other software architectures even existed), I would end up with very bloated controllers or even view models chock full of business logic that, had I been working on enterprise applications, would have made it difficult for other devs who were unfamiliar with my code to modify (i.e. more spaghetti).
One con I can think of is if you need really fast access to your data in your view (for example, game animation data like bone positions.) It is very inefficient to keep a layer of separation in this case.
Otherwise, for most other applications which are more data driven than graphics driven, it seems like a logical way to drive a UI.
If you follow the stackoverflow podcasts you can hear Jeff (and Geoff?) discuss its greatness. https://blog.stackoverflow.com/2008/08/podcast-17/. But remember that using these separate layers means things are easier in the future--and harder now. And layers can make things slower. And you may not need them. But don't let that stop you from learning what it is--when building big, robust, long-lived systems, it's invaluable.
It separates Model and View controlled by a Controller,
As far as Model is concerned, Your Models has to follow OO architecture, future enhancements and other maintenance of the code base should be very easy and the code base should be reusable.
Same model can have any no.of views e.g) same info can be shown in as different graphical views.
Same view can have different no.of models e.g) different detailed can be shown as a single graph say as a bar graph.
This is what is re-usability of both View and Model.
Enhancements in views and other support of new technologies for building the view can be implemented easily.
Guy who is working on view dose not need to know about the underlying Model code base and its architecture, vise versa for the model.
One of the major advantages of MVC which has not mentioned here is that MVC provides RESTful urls which enables SEO. When you name your Controllers and Actions wisely, it makes it easier for search engines to find your site if they only take a look at your site Urls. For example you have a car sale website and a page which displays available Lamborghini Veneno cars, instead of having www.MyCarSale.com/product/6548 referring to the page you can choose www.MyCarSale.com/SportCar/Lamborghini-Veneno url for SEO purpose.
Here is a good answer to MVC Advantages and here is an article How to create a SEO friendly Url.
Main advantage of MVC architecture is differentiating the layers of a project in Model,View and Controller for the Re-usability of code, easy to maintain code and maintenance. The best thing is the developer feels good to add some code in between the project maintenance.
Here you can see the some more points on Main Advantages of MVC Architecture.
![mvc architecture][1]
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.

Resources