Buscar en este blog....

Mostrando entradas con la etiqueta Modelación. Mostrar todas las entradas
Mostrando entradas con la etiqueta Modelación. 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, 3 de septiembre de 2010

La estrategia del Cartógrafo

Todos los que hayan leido el conocido libro de Craig Larman "UML y Patrones", ya saben a que me refiero. Para quienes no, y para tenerlo en mi colección bloggera de temas interesantes, lo pongo.

La estrategia del cartógrafo está explicada en la parte del libro que habra sobre la construcción de modelos conceptuales. La idea que propone es tener en cuenta tres sugerencias que seguir al momento de trazar un mapa o, en nuestro caso, modelar un dominio.

Un modelo conceptual es una especie de mapa de las cosas del dominio que estamos analizando. Las tres sugerencias para tener en cuenta son:

1) Utilizar los nombres existentes en el territorio. Los cartógrafos utilizan los nombres que se usan en ese territorio, no les inventan nuevos nombres a las cosas. Es decir, que el vocabulario que usemos cuando asignamos el nombre a los conceptos y atributos sea el mismo que se usa en el dominio. Por ej: si en un modelo de supermercado, el personal llama "Comprador" a los clientes, nosotros le llamaremos como tal y no "Cliente" o "PersonaQueCompra" o cualquier otro nombre que nos guste más.

2) Excluir las características irrelevantes. Los cartógrafos deben omitir en su mapa las cosas que no les parecen importantes, es decir, aquellas que no contribuyen con el propósito que persiguen, como por ejemplo, la población en determinados lugares, o la salinidad de la tierra, etc. En nuestro ámbito, y siguiendo con el ejemplo del supermercado, nos puede convenir excluir conceptos como "Proveedor" si es que los proveedores no son relevantes para los requerimientos actuales. Hay que tener cuidado en esto, porque algunos conceptos pueden no ser tan obvios respecto de su relevancia, y podemos omitir algo que en el futuro será necesario.

3) No agregar cosas que no existan. El ejemplo que se menciona en el libro no puede ser más claro: ¡un cartógrafo no va a poner una montaña si ésta no existe! Con esto se refiere a que es conveniente excluir todo aquello que no forma parte del dominio del sistema que se analiza.

Claro no hay que cumplirlas al pie de la letra (por algo son sugerencias) pero a mi parecer son muy simples y muy prácticas. A veces hasta pueden sonar obvias e innecesarias, pero lo que me agrada es que son muy útiles para esos momentos en que el sistema "nos puede", esos momentos en que nos perdemos en el mar de conceptos, requerimientos y descripciones que tienen los sistemas grandes...

Hasta la próxima.

martes, 11 de septiembre de 2007

Modelación Científica (I)

Actualmente me encuentro realizando un curso de posgrado sobre Modelación Científica, y me gustaría poder compartir algunas cosas del curso. Lamentablemente, no puedo compartir todas debido principalmente al típico problema de los derechos de autor: los apuntes sólo están disponibles para aquellas personas que han pagado para tomar el curso. Si me es posible, al finalizar el cursado (y haber rendido ;) voy a publicar los apuntes (soy partidario de que el conocimiento no debe restringirse, sino que debe ser gratuito y al alcance de cualquiera).

OK, para comenzar, quiero comentar sobre la primera práctica que he realizado. Se trata de un programa extremadamente simple en C++ que permite modelar el crecimiento poblacional de una región. En mi caso, de la provincia de Mendoza, Argentina de la cual soy residente. Utilizando datos oficiales, logré resultados muy aceptables, teniendo en cuenta la simplicidad del modelo.



El modelo de la imagen es el que yo diseñé para la simulación. Es muy simple de entnder:

Tenemos dos tipos de tasas: tasas de Mortalidad y tasas de Transferencia. La tasa de natalidad está en este último grupo. Las tasas de transferencia, (con índices inventados por mí ;) son necesarias para representar el porcentaje de cada población que "crece" y deja de existir en un grupo para pasar al siguiente. La codificación algorítmica o numérica del modelo es muy sencilla, ya que se trata de un modelo lineal. La línea punteada que une la población de Adultos con la Tasa de Natalidad, es debido a que suponemos que las mujeres Adultas (únicas con capacidad de procereación) pueden dar a luz un cierto número de individuos (niños). Son datos muy dependientes entre si; y por eso los uní con la línea; porque no es tan obvio como con las transferencias.

Sea pninos la población de niños y padultos la población de adultos; t_nat, t_mortN, t_transfNA las tasas de Natalidad, Mortalidad de Niños y Trasnferencia Niños-Adultos respectivamente:

pninos = pninos + (t_nat*padultos*0.5) - (t_mortN + t_transNA) *pninos

Suponiendo el que el 50% de los adultos procrean, es decir, el 50% son mujeres (de allí viene el 0.5)

Acá tenemos un ejemplo de la gráfica que nos genera excel con los puntos obtendios del programa de simulación realizado en C++ (el eje de ordenadas indica población, y el de absisas años):



No he puesto el link al programa porque he tenido serios problemas para subirlo, asique esto quedará para otra oportunidad.

Espero que le haya resultado tan interesante como a mí. Próximamente publicaré un par de cosas más, como los modelos: caza-predador.

Saludos, hasta pronto.