Saturday, December 25, 2010

Model View Controller MVC

MVC stands for Model-View-Controller.

Every application can be broken into three parts - the presentation layer (UI), the core business logic (aka domain logic) and the persistence layer (can be a RDBMS or a Directory Server, etc.). MVC targets at separating the presentation layer from the business logic layer (assume persistence to be a part of the BL layer for the time-being).

Model represents the Business Logic and the View represents the presentation layer. Coming to the Controller, it is the component which bridges the gap between these layers. I guess I can make it more clear using an example. Lets say I am building a desktop application which contains a button and on its click I store some data. The UI part and the button-click will be a part of View and the method doing the storing part will be a part of the Model.

However the UI will not call this method directly. The UI will call a method of the controller which will in turn call the storing method. Such a methodology will isolate the Business Logic from the UI logic. The advantage of this isolation is that migrating my desktop application to a web application would require only my UI code to rewritten.

Why would I want to do this through a controller? - One case may be doing formatting logics at the controller so that the BL layer focuses on the domain logic. Another case can be the BL may be a Web Service, the controller can contain code to setup the connection and call the web service methods and the UI can call the controller methods without even knowing that it is going through a web service. Possibilities are limitless.

Here's a good example which shows a live MVC - http://www.codeproject.com/KB/tips/ModelViewController.aspx.

However coming to .NET - WinForms use a slightly modified version of MVC called MVP - http://en.wikipedia.org/wiki/Model_View_Presenter and for WPF another version called MVVM - http://en.wikipedia.org/wiki/Model_View_ViewModel.

No comments:

Post a Comment