Saturday, May 18, 2013

Model – View Separation




Our team was waiting outside a food stall starring at the list of snack items that was put up on the board. I read one by one that was listed, and at one point my eyes stopped at “Cutlet”. “I will go with cutlet”, I said. The billing person (Lets call him the controller for now; as to why so, will be told shortly) nodded his head and proceeded to bill it. Then there came a notification from someone from the kitchen premises that cutlets were all over. Now, if the cutlets represented the actual “model”, the display board was the view. So, now I’ve explained why the billing person is the “controller”. Now if the controller had promptly informed the view about the change in the model, things would not have gone for a toss. (I know it is not something that is catastrophic, but still)

Model – View - Controller (MVC) pattern is awesome I tell you. When I was new to this pattern, I saw MVC as one among the many patterns available, but now I see it as a master pattern, the pattern that solves “data-here-display-how” problem. Let us see how MVC applies to different problems.

Firstly, I’ll talk about the files in a file system. We get to see many views of the file system- one as a general file system explorer, one as a tree structure, one as a file picker / saver dialog et al. The model is the same – the file system; the views are different.


(The tree view and the flat view of the file system)

(The file saver/picker view of the file system)

PhpMyAdmin, a tool to handle the administration of MySQL provides a view of the data in the database system. You may also wish to open a console and connect to the MySQL server. My aim here, is to explain how the model being same, is rendered in different views.

Let’s move on to few real life examples. The cutlet-board-hotel thing was one. Now, let me talk about, hmm say X-rays? X-ray gives a “view” of the actual model, the bone. 



We need to keep in mind that only “updatable” views result in change of the model information. Now, if your hand is broken, and you think you can change the X-ray image to fix the broken hand, my friend, it’s an epic fail attempt. And when you work on say, PhpMyAdmin, you can update a table, by updating the view (Hey not the SQL view, I am talking about the front end view you see on the browser), of course if only you got the permission for it. (Forget Jee-Boom-Bah pencil now)

My message to the computer science world: apply MVC pattern, it makes life simple and easy. Long live MVC! Long live MVC!

Cheers!

- ∫.∫rikrishnan