I understand that the model should generally consist of data manipulation and the view for data display from the model, but how do I keep my model and view layers decoupled?
My simple view has a few tables that display data. Its associated model manipulates the data based on the view’s type of TableModel
. Most of its methods involve using the TableModel
type. Should the view generally “breakdown” the data into a more generic type of integers and strings for the model? Therefore all the model handles are simple generic lists of data without needing to use TableModel
in case the view is changed into another interface. The model should be “unaware” of the view for good programming practices, right? If I change my view to a command-line interface, the associated model should still be able to perform its functions, given the correct associated Lists of integers/strings/whatever.
2
The first thing to understand is that the decoupling between model and view is only one-way. The model should not care how its data is presented to the outside world (it should be unaware of the view other than possibly knowing something is observing the model).
The view on the other hand does have knowledge about the model, in particular about how to get data out of it.
In an ideal world, the model should expose its data in a way that is convenient for the model and the concepts it represents. The view has to conform to the API of the model.
In the real world, people will want to reuse widgets across different projects, so you get libraries of widgets that expect a certain common API from the model they work with, often in the form of a generic abstraction such as a list, table or tree. In such cases, it is often easier to let the model reflect the generic abstraction it fits best with (with the associated common API) and to augment the interface where appropriate.
Although the model’s API has been adapted to meet common view expectations, the two are still decoupled, because the model does not know which portion of the model gets actually presented in the view and how it gets presented.
2
You’re missing a layer. You need a controller. The controller’s job is to take data from the model, whatever your model abstraction might be, and to then use that data to populate the view, do page logic, etc. MVC is the traditional model/view paradigm. My web application, here, is written in python and takes aadvantage of an MVC framework called Web.py. You can see the way the models and the views are separated by a controller layer, who controls the view.