Buscar en este blog....

Mostrando entradas con la etiqueta MVC. Mostrar todas las entradas
Mostrando entradas con la etiqueta MVC. Mostrar todas las entradas

domingo, 31 de julio de 2016

The Difference (and relationship) between MVC and MVP patterns

I wrote this post like one year ago, but I did it in spanish. Yet I'm trying to write also a little more in english. So here it goes.

I think this topic is normally a bit confusing due to the big amount of information that we can easily find in the internet and the short time we can spend to analyze all this information.

The MVC Pattern (Model-View-Controller) is a well-known design pattern which is being used all around the world. In fact, there's no one in the software development who hasn't hear about it. So I'm not gonna explain it. Nevertheless, not so well known is this other pattern called MVP (Model-View-Presenter), although it has gained more terrain in the last years.

At first view one can be tempted to think "Oh, they only changed the Controller of the MVC for the Presenter of the MVP, so it's almost the same thing, but with another name!".

Well.. nothing more far away from the truth! Absolutely not! So, what is it? What is the real difference between them? While I'm not gonna explain the MVP pattern in detail, because there is A LOT of information in internet, I would like to explain what is the relationship between these two patterns. How I see it.

First of all, let's quickly remember what the MVC is about: to separate an application into three conceptually-different parts, so he have:


  • Model: makes reference to data or, better said, to representation of the information. Depending on how you interpret the pattern, the model can be directly bound to the persistence of this information. But in a wider interpretation, it can also mean the whole state of the system in a given moment. So, in its wider interpretation, we can say it embraces both the state of the system and its persistence.
  • Controller: represents the business logic. The rules on which the systems run..
  • View: represents the user interface.

Here it is worth to mention that I don't particularly agree with the separation between "Model" and "Controller", because I think often is kind of difficult -and expensive in terms of time- to totally exclude the model (the data) from the controller (the business logic i.e. the behaviour). However, I'm not saying it can't be done, but rather consider that there is actually a conceptual separaration between them, althought it might be unnecesary (this will be inherent to each situation and system).

Now let's briefly review the what the MVP pattern is about:



  • Model: this model represents the business model. Violá! It's not the same as the model of the MVC, but rather this model includes both the representation of the data and the business logic. That's why we talk about a "Business Model". That is, this model invovles the Model and the Controller of the MVC together.
  • Presenter: this is the director: on one hand it directs the events of the view to the model and on the other it updates the view with the information coming from the model. This concept does not exists directly in the MVC pattern. I mean directly, because is perfectly valid to affirm that this "Presenter" is a part of the "View" in the MVC pattern. That is, this is the logic that we are used to write into the MVC's View, no matter how basic it is!
  • View: The View, according to the MVP, is the silliest and easy-to-write code that we have.  It's just about a "View" that knows his "Presenter", to whom it delegates absolutely everything that happens in it. This View makes nothing but to delegate. The user clicks, the "View" tells the "Presenter" where did the user click. Or the other way: the "Presenter" tell the "View" to fill a ComboBox, the "View" fills the Combo with the information provided. It just does not have business logic at all!

So having this information, if we analyze it a little, we come to the conclusion that both patterns are not mutually excludent. It is not about predicting "We're using the MVC pattern or the MVP pattern", but it could be interesting thinking in a combination of them. That might lead us to something called VPCM (View-Presenter-Controller-Model).

What?! Does it actually exists?! What are we talking about?

Nothing new, to be honest. Maybe the name it's new, it doesn't even exist. But that's not the point. The point is that we are breaking down the View of the MVC in two parts: a "View" who does nothing (but to delegate) and its "Presenter" who does everything for the view. Those are, the View and the Presenter of the MVP. Something like this:


Another way to see this, is the other way: we take the Model of the MVP and we break it down in two new pieces: a Controller (which has the business logic) and a Data Model (which represents the  information). That is, we've just get the Controller and the Model of the MVC pattern. It looks something like this:



As we can see after this analysis, they are NOT mutually excludent patterns: they complement each other! We could say that one emphasize
the Backend, and the other the Frontend. MVC and MVP respectively.

I would like to have some opinions about this analysis and its conclusion.
Cheers!

viernes, 21 de agosto de 2015

Diferencia -y relación- entre los patrones MVC y MVP

Creo que este tema se presta un poco a confusión debido a la cantidad de información que existe en internet y el poco tiempo que disponemos para analizar toda esta información.

El patrón MVC (Modelo-Vista-Controlador) es muy utilizado y creo muy pocas personas del ambiente del desarrollo no lo conocen, por lo que no voy a hablar de este patrón.

Sin embargo, no tan famoso es éste otro patrón, que ha tomado un poco más de fuerza desde hace unos años, y sigue escalando: el patrón MVP. El patrón MVP hace referencia a: MODELO-VISTA-PRESENTADOR.

A simple vista, uno se siente tentado a pensar: "Ah! Cambiaron el Controlador del MVC por algo nuevo llamado Presentador, que debe hacer algo parecido pero con otro nombre.."

Ja! Nada más alejado de la realidad! Absolutamente no! Entonces, ¿qué es?

Si bien no voy explicar qué es, porque sería seguir agregando más información de lo mismo, y en google ya hay mucha y buena, yo quiero hablar sobre qué relación existe entre ambos patrones, y por ende, también hablar de cuál es la diferencia.

Primero que nada, recordemos rápidamente que la intención del MVC es separar una aplicación en tres partes fundamenales, pero de alguna manera relacionadas. Tenemos:

  •  Modelo: que hace referencia a los datos o, mejor dicho, a la representación de la información. Según cómo se interprete el patrón, el modelo puede estar directamente ligado a la persistencia de dicha información. Sin mebargo, en una interpretación más amplia, puede abarcar también el estado del negocio en un momento dado. Es decir que, en su versión más amplia, el modelo es el estado del negocio y la persistenca de ese estado.
  • Controlador: que representa la lógica del negocio. Las reglas que hacen al negocio.
  • Vista: que representa la interfaz con el usuario.

Acá quiero aclarar que yo particularmente no estoy muy de acuerdo con la separación entre "Modelo" y "Controlador", porque pienso que muchas veces es dificil y costoso excluir totalmente al modelo (representación de los datos) de la lógica del negocio (o sea, del controlador). Sin embargo, no estoy diciendo que no se pueda hacer, o no se deba hacer, sino más bien que hay que considerar que existe una separación coneptual de ambas cosas, sin que esto implique necesariamente llevarla a cabo (aspecto que será inherente a cada situación).


Ahoa bien, si repasamos brevemente el MVP, nos encontramos con lo siguiente:


  • Modelo: aquí el modelo representa el modelo del negocio. Voilá! No es lo mismo que el modelo del MVC, sino que este modelo incluye tanto la representación de los datos como la lógica del negocio: por eso hablamos de "modelo del negocio".  Es decir que este modelo abarca al Modelo y al Controlador del MVC juntos.
  • Presentador: El presentador es quien dirige: por un lado los eventos de la vista hacia el modelo, y por otro lado actualiza la vista con las información provenientes del modelo. Este concepto no existe directamente dentro del patrón MVC. Digo "directamente" porque es perfectamente válido afirmar que este presentador es parte de la Vista del MVC. Es decir, es la lógica que le solemos poner a la vista, por más básica que sea!
  • Vista: La vista, según el MVP, es lo más tonto y fácil del programar que hay. Se trata de una vita propiamente dicha que conoce a su presentador, a quién le delega absolutamente todo. Ella no hace nada, excepto delegar. Ocurre un click: le dice al presentador que se haga cargo del click. Asi de simple. Ocurre algún otro evento: le dice al presentador que se encargue de ese evento. Pero ella no procesa nada, no hace nada. Solo delega el trabajo al presentador.

Despues de analizar un poco esto, podemos llegar a la conclusión de que ambos patrones no son excluyentes. No es cuestión de decir Vamos a usar el MVC o el MVP, sino más bien, puede ser interesante pensar en una combinación de ambos. Algo así como un VPCM (Vista-Presentador-Controlador-Modelo).

Qué!? Eso no existe! De qué estamos hablando?

De nada nuevo, en realidad. Sólo estamos desglosando la Vista del MVC en dos partes: una vista que no hace nada, y su presentador que hace todo. Es decir, de la Vista del MVC obtenemos la Vista y el Presentador del MVP. Algo así:


 
Otra forma de verlo, es la inversa: agarramos el Modelo del MVP y los desglosamos en un controlador (con la lógica del negocio) y un modelo de datos (represetación de los datos). Es decir, del Modelo del MVP obtenemos el Controlador y el Modelo del MVC. Algo así:



Cómo podemos ver después de este análisis, NO son patrones mutuamente excluyentes: son complementarios. Por decirlo así, uno hace más hincapié en el back-end, y el otro en el front-end.
Me gustaría leer opiniones que aporten a este análisis y ésta conclusión.
 Saludos!