Tuesday, September 3, 2013

Model-View-Controller (MVC) Done Right?

I was pleasantly reminded of how I, as a budding junior software engineer (a couple of years back), misunderstood MVC and application architecture, and how others may misunderstand this too. So, please allow me to explain my journey in understanding MVC better.

MVC and Application Architecture

Martin Fowler provides a good explanation of MVC in his Patterns of Enterprise Application Architecture.

When developing applications, one application architecture I'm usually exposed to is the layered architecture (also known as multi-layered, or multi-tiered). Each layer would usually be dependent on layers underneath it, but not above it. These layers provided abstraction (via interfaces), which is useful in tackling complex systems and allowing concurrent development.

A multilayered software architecture is a software architecture that uses many layers for allocating the different responsibilities of a software product.

Presentation Layer
Business Layer
Data Access (or Infrastructure) Layer

Missing Link Between MVC and Layered Architecture

So, I started thinking that MVC was mapped to layers like this:

LayerMVC Component
Business (or Domain)Controller
Data AccessModel

But that's the wrong way! A crucial point that I missed is that MVC is a presentation layer pattern. It is really intended for the user interface. So, what did I end up doing?

Because of this poor understanding of MVC, I ended up exposing domain entities as models to my views. This resulted in entities that exposed setters and getters, which made it difficult to implement invariants and DDD. This also resulted in business rules that were mixed with UI-related implementations. So, what is a better understanding of MVC?

Business (or Domain)Services / Domain Objects
Data AccessDAO / Repository Implementations / Gateways

As it was originally intended, MVC is found inside the presentation layer. It's important to note that the Model in MVC is not your Service Layer or the Domain Objects. It's the user interface's state (or View state).

If your application is simple enough, you could choose to have domain objects (usually entities) as your view state for simplicity. But please don't confuse MVC's Model with the Domain Objects.

If you find yourself having difficulty dealing with entities (or domain objects) in the presentation layer, perhaps you can consider converting domain objects to more portable DTOs that can be tailored to specific use cases (or specific UIs) and add an application service (typically using a facade pattern) that would handle the DTO-serializing responsibilities before exposing them to the presentation layer.

No comments:

Post a Comment