MVC and Tell Don’t Ask Principle – How Does MVC Work with Tell Don’t Ask?

design-patternsjavamvcobject-oriented

Procedural code gets information then makes decisions. Object-oriented
code tells objects to do things.

Alec Sharp

So, when a view wants to display some information that is suppose to be derived from properties of a model it is displaying, should the calculation be part of the model or the view?

Ideally the view should tell the object about the information it needs, and model should do the calculation and return the result.

But now, should the model start having new methods every time a new type of view wants to display extra information which is derived out of the model's property?

Should such methods be in the view or in the model? Or in such cases should we subclass the model, add the required methods, and then assign it to the view?

I am an Objective-C developer, I can also add a category to the model for the view but in languages where we don't have features where we can add methods to objects and classes at runtime, what is the ideal design?

Or are models in MVC meant to be just information in key-value pairs instead of real objects to be passed around, where a view reads each value based on a getter?

Best Answer

Ideally view should tell the object about the information it needs, model to should do the calculation and return the result.

That maybe an object oriented way, but not MVC. In MVC, the view typically sends a message to the controller "I want to display information", and the controller does the calculation using the model (or using model attributes or functions). Afterwards, the controller sends the result message back to the view (typically using an interface to decouple from the concrete kind of view).

but now, should model start having new methods every-time a new type of view wants to display extra information which is derived out of model's property?

Information derived out of model's property can be calculated either

  • in the model
  • in a controller using the model

I would place such calculation functions in the model only if they are not view-specific and have a certain chance of beeing reused. Functions totally specific to one view are better suited for the corresponding controller.

Related Topic