Getting started with software design using MVC, OO, and Design patterns [closed] - model-view-controller

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 6 years ago.
Improve this question
NOTE:
This question has been updated to provide more detail and insight than the previously.
UPDATE:
I just want to say thank you to everyone who responded. I'm still pretty much in the dark on what design pattern would work best for the Widget. Perhaps one of the Factory or Builder patterns?
I am just getting started on a new project and need to use MVC, OO and design patterns.
Here's the idea: Imagine a page that displays a set of widgets. These widgets are (usually) charts that are based off of data contained in several separate tables in the database. I use a running example of page that reports on a student's performance.
High Level Requirements
a page that displays a set of (HTML only) widgets.
widget's data will be based off a database query.
the page can be used to view separate datasets containing similarly laid out data. For example, a single page will display widgets that report on various aspects of a single student's performance.
want to see another student's performance, pull up another page. Displaying different widgets for different students is not needed (though it may be nice to have later).
There may be many students, but data contained in the database is similarly laid out for all students.
the way a widget is displayed may be changed easily (say changing a widget from displaying as a pie chart to display as a bar chart).
widgets should be able to be created quickly.
Low Level Requirements
Currently data does not change so widgets will not need to automatically update themselves.
Widgets may represent a ratio of two things (eg. a ratio of failed tests to successful tests as a pie chart), a series of points, or sometimes a single numeric value.
Development of new widgets should be a breeze, existing code need not be modified.
Framework to be used: Zend Framework, based on MVC.
There are (minimally) three things to define a widget: the dataset to report on (in the example above, the student ID), the query that describes the metric being reported, and a render mode (barchart, timeseries etc).
Here is a pass at breaking down the responsibilities of each layer of the MVC:
View: Zend views are HTML templates with PHP injected. They will contain one of several types of widgets. Widgets are of various forms including: static JPEG images (loaded from a remote site ie: <img src="http://widgetssite.com?x=2&y=3"/>, JSON based javascript widgets, or charts of various kinds (piechart, bar chart etc.)
Controller: Creates the widgets, assigns them to the view afterwards. The set of widgets that is to be displayed on a page needs to be maintained somewhere. Since I can't think of a good way to do this in the view, I'll add this to the controllers responsibilities for now. If there's a better place for this please shout. The controller will also have to handle any other input parameters and passing them to the widget. For example, the data_set id which may be passed at the url line as http:/.../report/?student_id=42
Model: The model, in the Zend Framework, is responsible for pulling the data and as such will most likely contain a class for each widget for accessing the database.
Some points:
The model here, represents the data for a particular widget. So necessarily, it will need to know what the query is going to be, in order to pull together the tables necessary to fetch that data.
There's an additional processing step that will most likely be necessary before the widget can present the data. This is dependant upon which renderer will be used. Sometimes it may require forming a url out of the data returned. Other times, a JSON array. Other times perhaps creating some markup. This can go either in the model or the controller or the view. Unless anyone can think of a good reason to move it to the controller or view, it is probably best to let this live in the model and keep the view and controller thin.
Likewise, a widget will be made up of 3 things, its parameters, its data, and its renderer.
One big part of the question is: What's a good way to represent the widget in an Object Oriented design? I already asked this once, couldn't get an answer. Is there a design pattern that can be applied to the Widgets that makes the most sense for this project?
Here's a first pass at a rather simple class for the Widget:
class Widget{
//method called by the view
render() {//output the markup based on the widget Type and interleaved the processed data}
//methods called by the controller:
public function __construct() {//recieve arguments for widget type (query and renderer), call create()}
public function create() {//tell the widget to build the query, execute it, and filter the data}
public function process_data() {//transform into JSON, an html entity etc}
//methods called by the model:
public function build_query() {...};
public function execute_query() {...};
public function filter_data() {...};
}
Looking at it, I can already see some problems.
For example, it is straightforward to pass the widget that was created in the controller to the View to render.
But when it comes to implementing the model it seems not so straight forward. Table Gateway Pattern is simpler to implement than ORM. But since table gateway pattern has one class for each model/table it doesn't seem to fit the bill. I could create a model for a particular table, and then within that, instantiate any other models needed. But that doesn't seem so to fit the Table Gateway Pattern, but rather ORM pattern. Can Table Gateway Pattern be implemented with multiple tables? What alternatives are there? Does it make sense that the controller creates the widget and the widget creates the Model?
Another issue that arises is that this design does not enable ease of widget creation. ie. Say I wanted to create a PiechartWidget, how much code can be reused? Would it not make more sense to use some OO ideas such as an interface or abstract classes/methods and inheritance?
Let's say I abstract the Widget class so only the shared methods are defined concretely, and the rest are declared as abstract methods. Revising the Widget class to make it abstract (second pass):
abstract class Widget{
private $_type;
private $_renderer;
//methods called by the controller:
//receive arguments for widget type (query and renderer),
protected function __construct($type, $renderer) {
$this->_type = $type;
$this->_render = $renderer;
$this->create();
}
//tell the widget to build the query, execute it, and filter the data
private function create() {
$this->build_query();
$this->execute_query();
$this->filter_data();
}
//methods called by the model:
abstract protected function build_query();
protected function execute_query() {
//common method
}
abstract protected function filter_data();
//method called by controller to tranform data for view
//transform into JSON, an html entity etc
abstract protected function process_data();
//method called by the view
//output the markup based on the widget Type and interleave the processed data
abstract protected function render();
}
Is this a good design? How could it be improved?
I assume writing a new widget will require at least some new code to build the query, and maybe filter the data, but it should be able to use preexisting code for almost all of the rest of its functionality, including the renderers that already exist.
I am hoping anyone could provide at least some feedback on this design. Validate it?
Tear it apart. Call me an idiot. That's fine too. I could use any forward traction.
A few specific questions:
Q1. What's the best way to implement the renderers, as part of the Widget class or as a separate class? 1a. If separate, how would it interact with the widget class(es)?
Q2. How could I improve this design to simplify creation of new kinds of widgets?
Q3. And lastly, I feel like I am missing something here with regards to data encapsulation. How does data encapsulation relate to the requirements and play out in this scenario?

For #2, if you are using WPF on windows, or Silverlight in general, consider using MVVM pattern (Model-View-ViewModel), here is explanation with a WPF implementation:
MVVM at msdn
For #1 (comments not answer): For exact implementations (and minor variations) of MVC, it really depends on what language you are using.
Another alternative to MVC is MVP Model View Presenter
Remember the goal of OO is not to cram design patterns into your code, but to create maintainable code with less bugs/increased readability.

High Requirements
- a page that displays a set of widgets. widgets are based off of data contained in several separate tables in the database.
- widget's data will be based off a database query. widget display its data in a particular way.
- widgets should be able to be created quickly.
Low Level Requirements
- Data changes, multiple charts need to change, push model (from data to ui)
- Development of new widgets should be a breeze, existing code need not be modified
Advice from design patterns basics
- MVC supports one to many notification pattern, so yes, once your widget is initialized, created and connected to the web page, it should wait for notifications from the database.
- Strategy pattern, your entire code should develop to a interface. New widgets should be added to a parametrized LinkedList (or some other data structure). That way new widget developers just implement the interface and your framework picks up these notifications without change to existing code.
Siddharth

The purpose behind all of these ideas -- MVC, patterns, etc. -- is essentially the same: every class should do one thing, and every distinct responsibility in your application should be separated into distinct layers. Your views (page and widgets) should be thin and make few if any decisions other than to present data gathered from the models. The models should operate on a data layer agnostically, which is to say they should not know whether the source of their data is a specific kind of data source. The controllers should be thin as well, acting basically as a routing layer between the views and models. Controllers take input from the users and perform the relevant actions on the models. The application of this concept varies depending on your target environment -- web, rich client, etc.
The architecture of the model alone is no trivial problem. You have many patterns to choose from and many frameworks, and choosing the right one -- pattern or framework -- will depend entirely on the particulars of your domain, which we have far too few of here to give you more specific advice. Suffice it to say it is recommended you spend some time getting to know a few Object-Relational Mapping frameworks for your particular technology stack (be it Java, .NET, etc.) and the respective patterns they were built on.
Also make yourself familiar with the difference between MVP and MVC -- Martin Fowler's work is essential here.
As for design patterns, the application of most of the standard GOF patterns could easily come into play in some form or another, and it is recommended you spend time in Design Patterns or one of the many introductory texts on the subject. No one here can give specific answers as to how MVC applies to your domain -- that can only be answered by experienced engineers in cooperation with a Product Owner who has the authority to make workflow and UI decisions that will greatly affect such decisions in their particulars.
In short, the very nature of your question suggests you are in need of an experienced OOP architect or senior developer who has done this before. Alternatively give yourself a good deal of time in intensive study before moving forward. The scope of your project encompasses a vast amount of learning that many coders take years to fully grasp. This is not to say your project is doomed -- in fact you may be able to accomplish quite a lot if you choose the right technology stack, framework, etc., and assuming you are reasonably bright and focused on the task at hand. But getting concepts as broad as "MVC" or "OO" right is not something I think can be done on a first try and under time constraints.
EDIT: I just caught your edit re: Zend. Having a framework in place is good, that takes care of a lot of architectural decisions. I'm not familiar with Zend, but I would stick to its defaults. Much more depends here on your ultimate UI delivery -- are you in a RIA environment like Flash or Silverlight, or are you in a strict HTML/JavaScript environment? In either case the controllers should still be thin and operate as routers taking user requests from HTTP gets and posts, and immediately handing off to the models. The views should remain thin as well and make as few decisions as possible. The concept of MVC applied in a web environment has been pretty well established by Rails and the frameworks that followed, and I'm assuming Zend is similar to something like CakePHP in this regard: the application server has a routing system that maps HTTP calls to controller actions that respond with specific views. The request/response cycle is basically this:
User request posted through a URL
Router hands control to a controller class
Controller makes a call to a model with the given params
The model operates on the data, posts back to the controller
The framework maps the finished data into a view, with some kind of code-behind that puts the results of the request in the view's scope.
The framework creates html (or xml or whatever) and posts back to the caller.

It sounds like you want to use MVC and other patterns because they are the new buzz words. Splitting your design among model view and controller should tell you how to spread the functionality of your application. Although I totally agree that using MVC is the correct approach, I suggest you research the pattern and look at some source code that implements it. As a start to your question though, the widgets that will be displayed will be your views, that much should be obvious. Input from the user, such as changing a parameter of some widget or requesting other information will come into your application and should be handled by a controller. A concrete example of this is a Java-based HttpServlet. The controller servlet receives the user request and asks the lower layers of your app (Service, Persistence, etc) for an updated representation of your model. The model includes all of your domain-specific objects (i.e the data from your databases, etc). This data (the updated model) comes back to the controller, which in turn pushes out a new view for the user. Hopefully that is enough to get you started about designing your app.
As further help, you could consider using a framework to assist in the development of your app. I like Spring a lot, and it has a first class MVC implementation that really helps guide you to designing a correct MVC web app.

You may consider using Subject Observer Pattern
Have your class, named DataReader as single Subject. Your multiple widgets will act as Observers. Once your DataReader receives data from server, it (Subject) will inform multiple widgets (Observer).
Your individual widgets may have different presentation to present to same set of data from DataReader.
Update
In the message where subject notify observer, you may include the message type information as well. Widgets will only process message type, which is within their own interest, and ignore rest of the message.

NOTE: This is my new answer based on new the updated question.
Here is a proposed class diagram. I'm going to work on a sequence diagram.
My old answer is here:
Based on the requirements you describe, your model is your database or data warehouse and your views are your pie charts, bar graphs, etc. I don't see the need for a controller, because it sounds like you have a one page dashboard with widgets.
You need to spend your time on the database model. Since you're doing all selects and no updates, go for a de-normalized data model that makes these queries efficient. You should put the results of these queries in a table type object (e.g. 2-dimensional array) or 3-dimensional array based on the amount of dimensions. You are limited to 3 dimensions unless you use animation.

Related

MVC - which methods should be in Model class except set/get members?

Should methods that manipulate the Model class members be implemented in the Model or in the Controller? Does it depend on how "heavy" this manipulation is ?
By "manipulation" I mean:
get a class member
make a long calculation based upon this class member
return another value which relates to this class
For example, a Board class which hold a cell matrix member.
Now I want to implement a method which returns all the surrounding cells according to specific cell location.
Is the model or view responsible to for implementing the above ?
If this question belongs to another Stack Exchange QA site I will welcome the recommendation to move my post to that site.
Keep your controllers thin, don't let them do much, this aligns with the Single Responsibility Principle in SOLID for Object Oriented Design. If you have fat controllers, they become hard to test and maintain.
As for the models, I used to have dumb models before that did nothing but to map to database tables and that was inspired by most of the sample applications that you see on the web, but now I don't do that.
I (try to) follow the principles from Domain Driven Design, where models (entities in DDD terms) are at the center of the application, they are expected to encapsulate behaviour related to the entity, they are smart models (so yes, the logic related to an object will live with it in that case). DDD is a much bigger topic and it is not related directly to MVC, but the principles behind it helps you better design your applications, there is a lot of materials and sample apps available if you google DDD.
Additionally, Ruby On Rails community - which seems to inspire most of MVC frameworks - also seems to have a hype around having Fat Models and Skinny Controllers.
On top of that, you can add View Models to your mix which I find helpful. In this case, you can have a ViewModel to represent a dumb subset of your model(s) just to use for generating the view, it makes your life easier and further separate your Views from your Models so that they don't affect your design decisions unnecessarily.
What you call "model" is are actually domain objects. The actual model in MVC is just a layer, not concrete thing.
In your particular example, the Board should have a method that returns this list. I assume, that you are actually acquiring it because you then need to do further interaction with those cells.
This is where the services within the model layer comes in to play. If you use them, they are the outer part of model layer and contain the application logic - interaction between different domain objects and the interaction between the persistence (usually either data mappers or units of work) and domain objects.
Let's say you are making a game, and you and player performs and AoE attack. Controller takes a hold of service, which is responsible for this functionality and sends a command: this player aimed AoE in this direction, perform it.
Service instantiates Board and asks for surrounding cells of the target location. Then it performs "damage" on every cell in the collection that it acquired. After the logic is done, it tell the Unit of Work instance to commit all the changes, that happened on the Board.
Controller does not care about the details of what service does. And it should not receive any feedback. When execution gets to the view, it request from model layer the latest changes and modifies the UI. As the added benefit - services let you stop the business logic from leaking in the presentation layer (mostly made up from views an controllers).
The domain object should contain only methods, that deal with their state.
I think this has little to do with MVC, and a lot more to do with regular software engineering.
I personally wouldn't hesitate to stick trivial calculations in a model, but would be extremely wary of fat models.
Now, the fact that MVC stands for Model View Controller doesn't necessarily mean that everything should be either a view, a model or a controller. If you feel the need to move responsibilities to a separate class that doesn't really qualify as an M, a V or a C, I don't see why you shouldn't do it.
The way you implement it is up to you. You could either use this separate class as a "top level" (for lack of a better term) object, or make a method of the model delegate to it, so as to hide the fact that you're using it. I would probably go for the latter.
Everything is debatable, though. Everybody and their sister seem to have a different opinion on how to do MVC right.
Me, I just consider it a guideline. Sure, it's a great idea because it leads you to a better separation of concern, but in the end—as it always happens—there's no one-size-fits-all way to apply it, and you should not be overly constrained by it, to the point where everything has to be either a view, a model or a controller.
As per best practice we should use properties for Calculated fields with get access only. example public double TotalCost {
get
{
return this.Role.Cost * TotalHour;
}
}

Generating Navigation for different user types, MVC, PHP

I have this idea of generating an array of user-links that will depend on user-roles.
The user can be a student or an admin.
What I have in mind is use a foreach loop to generate a list of links that is only available for certain users.
My problem is, I created a helper class called Navigation, but I am so certain that I MUST NOT hard-code the links in there, instead I want that helper class to just read an object sent from somewhere, and then will return the desired navigation array to a page.
Follow up questions, where do you think should i keep the links that will only be available for students, for admins. Should i just keep them in a text-file?
or if it is possible to create a controller that passes an array of links, for example
a method in nav_controller class -> studentLinks(){} that will send an array of links to the helper class, the the helper class will then send it to the view..
Sorry if I'm quite crazy at explaining. Do you have any related resources?
From your description it seems that you are building some education-related system. It would make sense to create implementation in such way, that you can later expand the project. Seems reasonable to expect addition of "lectors" as a role later.
Then again .. I am not sure how extensive your knowledge about MVC design pattern is.
That said, in this situation I would consider two ways to solve this:
View requests current user's status from model layer and, based on the response, requests additional data. Then view uses either admin or user templates and creates the response.
You can either hardcode the specific navigation items in the templates, from which you build the response, or the lit of available navigation items can be a part of the additional information that you requested from model layer.
The downside for this method is, that every time you need, when you need to add another group, you will have to rewrite some (if not all) view classes.
Wrap the structures from model layer in a containment object (the basis of implementation available in this post), which would let you restrict, what data is returned.
When using this approach, the views aways request all the available information from model layer, but some of it will return null, in which case the template would not be applied. To implement this, the list of available navigation items would have to be provided by model layer.
P.S. As you might have noticed from this description, view is not a template and model is not a class.
It really depends on what you're already using and the scale of your project. If you're using a db - stick it there. If you're using xml/json/yaml/whatever - store it in a file with corresponding format. If you have neither - hardcode it. What I mean - avoid using multiple technologies to store data. Also, if the links won't be updated frequently and the users won't be able to customize them I'd hardcode them. There's no point in creating something very complex for the sake of dynamics if the app will be mostly static.
Note that this question doesn't quite fit in stackoverflow. programmers.stackexchange.com would probably be a better fit

Why Qt is misusing model/view terminology?

I think that the terminology used in Qt with model/view controls is flawed. On their explanation page they state, that they simplified the MVC to MV by merging View and Controller and they are giving the following picture:
However I think, they misnamed the roles of objects and I think that,
What they call View with merged Controller is in fact a View only.
What they call Model is in fact Controller only.
If you really want to have a model it would be somewhere where their "Data" is.
I am speaking about usual and sane way you would use Qt model/view component in your app.
Here are the reasons:
This is typically Qt component which is used as is, without adding any Controller logic specific to your objects)
This is hardly a Model, just because you should implement several Qt methods like rowCount, columnCount, data etc. which have nothing to do with your model. In fact there are typical model methods found in Controllers. Of course, you can implement both Controller and Model logic here, but first it would be quite bad code design and secondly you would merge Controller and Model not Controller and View as they state.
As said in reason 2. if you want to separate Model logic that it is surely not the blue box on the picture, but rather the dashed "Data" box (communicating to real Data of course).
Is Qt wrong in their terminology, or it is just me who does not understand? (BTW: The reason why it is not academic question is that I have started to code my project following their naming and I have soon found out, that the code clearly is not right. It was only after that when I realized, that I should not try put Model logic in what they call Model)
Short answer
Qt's MVC only applies to one data structure. When talking about an MVC application you should not think about QAbstractItemModel or QListView.
If you want an MVC architecture for your whole program, Qt hasn't such a "huge" model/view framework. But for each list / tree of data in your program you can use the Qt MVC approach which indeed has a controller within its view. The data is within or outside of the model; this depends on what type of model you are using (own model subclass: probably within the model; e.g. QSqlTableModel: outside (but maybe cached within) the model). To put your models and views together, use own classes which then implement the business logic.
Long answer
Qt's model/view approach and terminology:
Qt provides simple views for their models. They have a controller built in: selecting, editing and moving items are something what in most cases a controller "controls". That is, interpreting user input (mouse clicks and moves) and giving the appropriate commands to the model.
Qt's models are indeed models having underlying data. The abstract models of course don't hold data, since Qt doesn't know how you want to store them. But you extend a QAbstractItemModel to your needs by adding your data containers to the subclass and making the model interface accessing your data. So in fact, and I assume you don't like this, the problem is that you need to program the model, so how data is accessed and modified in your data structure.
In MVC terminology, the model contains both the data and the logic. In Qt, it's up to you whether or not you include some of your business logic inside your model or put it outside, being a "view" on its own. It's not even clear what's meant by logic: Selecting, renaming and moving items around? => already implemented. Doing calculations with them? => Put it outside or inside the model subclass. Storing or loading data from/to a file? => Put it inside the model subclass.
My personal opinion:
It is very difficult to provide a good and generic MV(C) system to a programmer. Because in most cases the models are simple (e.g. only string lists) Qt also provides a ready-to-use QStringListModel. But if your data is more complex than strings, it's up to you how you want to represent the data via the Qt model/view interface. If you have, for example, a struct with 3 fields (let's say persons with name, age and gender) you could assign the 3 fields to 3 different columns or to 3 different roles. I dislike both approaches.
I think Qt's model/view framework is only useful when you want to display simple data structures. It becomes difficult to handle if the data is of custom types or structured not in a tree or list (e.g. a graph). In most cases, lists are enough and even in some cases, a model should only hold one single entry. Especially if you want to model one single entry having different attributes (one instance of one class), Qt's model/view framework isn't the right way to separate logic from user interface.
To sum things up, I think Qt's model/view framework is useful if and only if your data is being viewed by one of Qt's viewer widgets. It's totally useless if you're about to write your own viewer for a model holding only one entry, e.g. your application's settings, or if your data isn't of printable types.
How did I use Qt model/view within a (bigger) application?
I once wrote (in a team) an application which uses multiple Qt models to manage data. We decided to create a DataRole to hold the actual data which was of a different custom type for each different model subclass. We created an outer model class called Model holding all the different Qt models. We also created an outer view class called View holding the windows (widgets) which are connected to the models within Model. So this approach is an extended Qt MVC, adapted to our own needs. Both Model and View classes themselves don't have anything to do with the Qt MVC.
Where did we put the logic? We created classes which did the actual computations on the data by reading data from source models (when they changed) and writing the results into target models. From Qt's point of view, this logic classes would be views, since they "connect" to models (not "view" for the user, but a "view" for the business logic part of the application).
Where are the controllers? In the original MVC terminology, controllers interpret the user input (mouse and keyboard) and give commands to the model to perform the requested action. Since the Qt views already interpret user input like renaming and moving items, this wasn't needed. But what we needed was an interpretation of user interaction which goes beyond the Qt views.
I agree with you that Qt's naming is misleading. In my opinion however, the problem is not Qt's alone, but is shared by all frameworks that allow us to adhere to the principle of separation of concerns when implementing our UIs. When someone comes up with such a framework, and finds a good way to keep "things" separated, they always feel obliged to have modules that they call "Model" and others that they call "View". Over the years I have worked with these frameworks:
MFC
Qt
Swing
SWT
WPF with MVVM
If you compare how the terms "Model" and "View" are used in these frameworks, and what responsibilities the classes in the "View", the "Model", and the "Controller" (if there is one) have, you will find that there are very big differences. It would certainly be useful to have a comparison of the different concepts and terminologies, so that people switching from one framework to another have a chance to stay sane, but that would require a lot of work and research. A good read is Martin Fowler's overview.
Since there are so many different ideas what an MVC pattern can look like, which one is correct? In my opinion, the people who invented MVC should be turned to when we want to know how it is supposed to be implemented "correctly". In the original smalltalk paper it says:
The view manages the graphical and/or textual output to the portion of the bitmapped display that is allocated to its application. The controller interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate. Finally, the model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).
In light of that I would answer your three main concerns thusly:
In fact a Qt component "manages the graphical [...] output", and "interprets the mouse and keyboard inputs", so it could indeed be called merged View and Controller with respect to the definition above.
I agree that you are/would be forced to merge Controller and Model (again with respect to the definition above).
I agree, again. The Model should only manage the data of the application domain. This is what they call "data". Clearly, dealing with rows and columns for example has normally nothing to do with our applications domain.
Where does it leave us? In my opinion, it is best to figure out what Qt really means when the terms "Model" and "View" are used and use the terms in their manner while we are programming with Qt. If you keep being bothered it will only slow you down, and the way things are set up in Qt does allow elegant design - which weighs more that their "wrong" naming conventions.
The terminology isn't right or wrong, it's useful or useless.
You might change the question a bit and ask why Qt isn't more MVC-friendly. The answer to is that the early Qt developers believe that decoupling V from C in GUI applications makes for bad Vs and Cs both. QWidget's design tries to make it simple to bind mouse input interperation closely with pixel output decisions, and you can see how that's not the road towards MVC.
As Model function is to respond to requests for information, I think there is nothing wrong in defining such methods as rowCount, columnCount, etc. I think Model is some kind of wrapper for data source (no matter what is it SQL table or just an array), it provides data in standard form, and you should to define methods depends on your data source structure.
I believe their terminology is correct...although in real applications I find it can be very easy to blur the lines between model, view, and controller depending on your level of abstraction: one level's view may be a higher level's model.
I feel the confusion arises from their QAbstractModelItem class. This class isn't a model item, but rather it is an interface to a model. To make their view classes interface with the model, they had to create a generic abstract interface to the model. However, a model can be a single item, a list of items, a table of 2 or more dimensions of items, etc; so their interface has to support all these model variations. Admittedly, this makes the model items fairly complex, and the glue code to make it work with an actual model does seem to stretch the metaphor a bit.
I think that ... What they call Model is in fact Controller only.
No, their "model' is definitely not a controller.
The controller is the part of user visible controls that modify the model (and therefore indirectly modify the view). For example, a "delete" button is part of the controller.
I think there is often confusion because many see something like "the controller modifies the model" and think this means the mutating functions on their model, like a "deleteRow()" method. But in classic MVC, the controller is specifically the user interface part. Methods that mutate the model are simply part of the model.
Since MVC was invented, its distinction between controller and view has become increasingly tense. Think about a text box: it both shows you some text and lets you edit it, so is it view or controller? The answer has to be that it is part of both. Back when you were working on a teletype in the 1960s the distinction was clearer – think of the ed – but that doesn't mean things were better for the user back then!
It is true that their QAbstractItemModel is rather higher level than a model would normally be. For example, items in it can have a background colour (a brush technically), which is a decidedly view-ish attribute! So there's an argument that QAbstractItemModel is more like a view and your data is the model. The truth is it's somewhere in between the classic meanings of view and model. But I can't see how it's a controller; if anything that's the QT widget that uses it.

Using MVC, how should one handle communication between Views? Between Models?

Question number three in my quest to properly understand MVC before I implement it:
I have two cases in mind:
The primary application
window needs to launch the
preferences window. (One View
invoking another View.)
The primary Model for an application
needs to access a property
in the preferences Model. (One Model
accessing another Model.)
These questions are related in that they both involve communication across Model-View-Controller triplets, a topic that I haven't found much discussion of in my Googling.
The obvious way to fix this is to wrap everything in a top-level "application" object that handles transactions between Models and allows Controllers to invoke one another's methods. I have seen this implemented, but I'm not convinced its a good idea. I can also see possibilities involving Controllers observing more than one Model and responding to more than one View, but this seems like its going to become very cluttered and difficult to follow.
Suggestions on how best to implement this sort of cross-talk? I feel like its a very obvious question, but I've been unable to find a well-documented solution.
On a broader note, if anyone has a link that shows typical approaches to these sorts of MVC issues, I would love to see it. I haven't had much luck finding solid, non-trivial references. Examples in Python would be lovely, but I'll gladly read anything.
Edit 1:
I see some pretty interesting things being said below and in general no-one seems to have a problem with the approach I've described. It is already almost a lazy form of the FrontController design that Vincent is describing. I certainly don't foresee any problems in implementing that pattern, however, it doesn't seem that anyone has really addressed the question in regards to communication amongst Models. All the answers seem to be addressing communication among objects in a single Model. I'm more interested in maintaining separate Models for separate components of the application, so that I'm not stuffing fifty state properties into a single Model class. Should I be maintaining them as sub-Models instead?
With respect to (1), views don't invoke other views. They invoke controller actions that may result in other views being rendered. In your case, the primary application window contains a user interface element (button, link) that invokes a controller action to display the preferences window.
With respect to (3), model components certainly could be related to one another. This isn't unexpected nor to be avoided, necessarily. For instance your Customer model may have an associated set of Orders. It would be perfectly natural to access the customer's orders via a method in the Customer class.
You might want to take a look at the MVC page on wikipedia for an overview.
You may want to consider looking up the Front Controller design pattern.
The Front Controller pattern defines a single component that is responsible for processing application requests. A front controller centralizes functions such as view selection, security, and templating, and applies them consistently across all pages or views. Consequently, when the behavior of these functions need to change, only a small part of the application needs to be changed: the controller and its helper classes.
This way all requests from the view goes to the FrontController who then decides which specific action (controller) to invoke. Sometimes, it could forward straight to another view as in your first case.
There is no problem with multiple objects in the model talking to each other. In fact that will be very common. The way I see it, all the objects in the Model act like one component to represent the data and operations on the data.
This article might help. And this one.
Model does not mean a single model object. The model is the subset of the entirety of your domain model which is directly related to the controller actions and the views in question.

What is MVC (Model View Controller)? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I've heard the term MVC (Model View Controller) tossed about with a ton of Buzz lately, but what really is it?
You might want to take a look at what Martin Fowler has to say about MVC, MVP and UI architectures in general at Martin Fowlers site.
I like this article by Martin Fowler. You'll see that MVC is actually more or less dead, strictly speaking, in its original domain of rich UI programming. The distinction between View and Controller doesn't apply to most modern UI toolkits.
The term seems to have found new life in web programming circles recently. I'm not sure whether that's truly MVC though, or just re-using the name for some closely related but subtly different ideas.
MVC is a design pattern originally pioneered in the olden days of smalltalk.
The concept was that a model would represent your application state and logic, and controllers would handle IO between "Views".
A View was a representation of the state in the model. For example, your model may be a spreadsheet document, and you may have a view that represents it as a spreadsheet and a view that represents it as a pivot table.
Modern MVC has been polluted with fake MVC web junk, so I'll let others answer that.
Here is a naive description of MVC : http://www.devcodenote.com/2015/04/mvc-model-view-controller.html
A snippet:
Definition : It is a design pattern which separates an application into multiple layers of functionality.
The layers:
Model
Represents data.
It acts as an interface between the database and the application (as a data object).
It will handle validations, associations, transactions etc.
Controller
It gathers and processes data.
Handles code which does data selection and data messaging.
View
Displays output to the users.
MVC Design Pattern:
4 parts = User, View, Controller, Model.
User:
- sees the View and uses the Controller.
Model:
- holds the data and updates the Model that there is new data/state.
View:
- displays the data that the Model has.
Controller:
- takes the request from the user to get or set information, then communicates with either the View or Model, resp.
- it "gets" via the View.
- it "sets" via the Model.
As the tag on your question states its a design pattern. But that probably doesn't help you. Basically what it is, is a way to organize your code into logical groupings that keep the various pieces separate and easily modifiable.
Simplification:
Model = Data structure / Business Logic
View = Output layer (i.e HTML code)
Controller = Message transfer layer
So when people talk about MVC what they are talking about is dividing up there code into these logical groups to keep it clean and structured, and hopefully loosely coupled. By following this design pattern you should be able to build applications that could have there View completely changed into something else without ever having to touch your controller or model (i.e. switching from HTML to RSS).
There are tons and tons of tutorials out there just google for it and I'm sure you'll turn up at least one that will explain it in terms that click with you.
Wikipedia seems to describe it best so far:
http://en.wikipedia.org/wiki/Model-view-controller
Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements
The MVC or Model-View-Controller User Interface Paradigm was first described by Trygve Reenskaug of the Xerox PARC. In first appeared in print in Byte magazine volume 6, number 8, in August of 1981.
This What is MVC blog article on Oreilly has you covered.
MVC is a software architecture pattern that separates representation from user interaction.
Generally, the model consists of application data and functions that interact with it, while the view presents this data to the user; the controller mediates between the two.
It is a way of separating the underlying functionality of your application (model) from the way it interacts with the user (view). The controller coordinates how the model and view talk to each other.
Whilst it is all the rage at the moment, it is important to remember that preventing the model itself being able to determine exactly how its data is presented to the user can seen as a negative thing. The most obvious example is with HTML. The original intention of HTML was that there should be a clear separation of the model (HTML) from the view (rendered webpage) via a controller (the browser). There has been such a backlash against this original intention that browsers are criticised if they do not render a page pixel perfect to the designer's desired view.
MVC is a way to partition a user interface element into 3 distinct concepts. The model is the data on which the interface operates. The view is how the element is represented visually (or maybe audibly?). The controller is the logic that operates on the data.
For example, if you have some text you want to manipulate in a UI. A simple string could represent the data. The view could be a text field. The controller is the logic that translates input from the user - say character or mouse input - and makes changes to the underlying data model.
Like many have said already, MVC is a design pattern. I'm teaching one of my coworkers now and have explained it this way:
Models - The data access layer. This can be direct data access, web services, etc
Views - The presentation layer of your application.
Controllers - This is the business logic for your application.
This pattern enhances test-driven development.

Resources