Wednesday, March 25, 2009

One Thing I Still Don't Get About MVC

I've been using the new ASP.NET MVC framework lately, and loving it.  The app has cleaner markup and clear separation of concerns, and the various 'conventions' have let me focus on the business logic and UI.  But one thing still sort of bugs me about it, and that's the "ASP.NET" part.   One of the raison d'être of separation of concerns is to be able to reuse code as much as possible - Don't Repeat Yourself (DRY).  If my business logic is UI-agnostic, I should be able to easily reuse it in other UIs.  Yet for ASP.NET, controllers are still very UI-aware.  Sure, you can abstract the HttpContext away for unit testing, but it's still there, and thus the controller is not reusable in a WPF/WinForms scenario. 

In thinking this through, I began to suspect I was missing something vital.  Maybe I misunderstand SoC or DRY or MVC in general.  So I asked over on Stack Overflow, and the answers helped clarify some of the reasons ASP.NET MVC is not ".NET MVC".   First, the reality is some things are always going to be different between Web and Desktop.  Eduardo Molteni writes:

I have to say the the MVC model is specially practical in web apps, and that's because the view (the html page) is really disconnected and far away from the controler and the model. In desktop apps, that is not the case, and you will be soon missing some opportunities the break the pattern to make the app more useful. For example, you can't do the powerful and time-saver databinding in WPF, because it breaks the MVC pattern.

And user Ash makes the point:

If they had created a more general ".NET MVC" framework I would expect it would require a much more difficult trade-off between the needs of web applications versus desktop applications.

So, in a sense, re-usable controllers is pie-in-the-sky, ivory tower architecture.  Maybe possible, but given the two distinct natures of web and desktop apps, not always practical.  That's not to say ASP.NET MVC falls short.  Testability is one clear reason to keep controller logic and views separate.  Also I've found having a clear place for each concern to live helps me think about what is business logic, versus what is UI.  In the end, a little voice still tells me my code should be more reusable - perhaps by moving some logic out of the controllers and into reusable services- but I see now that's not always desirable or practical.

2 comments:

Steve said...

The way I learned Model-View-Controller is that the Model is the data model (the UI-agnostic part), the View is the presentation layer (windows/dialogs, dependent on the UI) and the Controller is the input/control mechanisms (again, dependent on the UI/hardware).

So I wouldn't expect the Controller part to be platform-agnostic.

Steve

for ict 99 said...
This comment has been removed by a blog administrator.