Is it ever really acceptable to reassign the model for a view in MVC? (Or MV* where applicable.) In other words, for a single view instance, is it ever ok to reassign the view's model? That is, as opposed to using setters (mutators) on the model so that it does not have to be reassigned. Under what conditions (if any) is this acceptable MVC design?
Here is an example in JavaScript, but the question is language-agnostic.
var Model = function (m) {
var message = m;
return {
getMessage: function () {
return message;
},
setMessage: function (m) {
message = m;
}
};
};
var View = function (m) {
var model = m;
return {
render: function () {
alert(model.getMessage());
},
setModel: function (m) {
model = m; // hmm, is this okay?
}
};
};
var model1 = new Model('hello world');
var view = new View(model1);
var model2 = new Model('hi there');
view.render();
view.setModel(model2); // reassign model
view.render();
model2.setMessage('hi again'); // mutate model via setter
view.render();
In the line view.setModel(model2);
, the model is reassigned (the approach in question). In the line model2.setMessage('hi again');
, the model is instead mutated via its own setter, which in my view seems generally preferred.
One of the main drawbacks I can see to model reassignment is that it could complicate attempts to reuse the model elsewhere in the application. In some MVC applications a single shared model could be used to drive multiple views (e.g. list, editor, and display views of the same data), in which case model reassignment would be problematic -- it would at least require the added complexity of communicating the model reassignment to dependent views. Here I think the DRY principle trumps the no-mutators principle. (Open to argument here.) Can an even stronger case be made?
To recap, under what circumstances might model assignment be acceptable, if any? Perhaps in certain languages, under extreme performance constraints...? Is "do not reassign models" a good rule of thumb? A pointer to an authoritative source or real-world situation would be helpful.