Getting rid of the all mighty Controller

Problem

MVC Controller easily becomes too complex resembling more Transaction Script than plain adapter. Although if using Spring it is possible to make controllers less dependent on underlying HTTP requests/responses they will still be tied to one logical presentation view (property which is inherent to MVC).

Also it is not very easy to test Controller as its public API is based on HTTP. Basically there are two ways to test Controller - either by mocking HTTP request and response or by extracting complex logic into separate methods that have more convenient arguments and test these methods separately. First way is a bit cumbersome. Downside of second approach is that as you don't test the actual API of your class tests won't be very useful as specifications. Also testing via internal methods is more fragile and not that reliable as via public interface.

Solution

Introduce Facade and move most complex logic out of Controller.

Following CRC cards describe the resulting design:

Controller  
Responsibilities Collaborators
  • binding request parameters to Command
  • filling Model with data got from Facade
  • forwarding Model to proper View
Command
Model
Facade
View
Facade  
Responsibilities Collaborators
  • transforming Command to domain specific request and forwarding it to Services or Entities
  • if needed transforming responses from domain layer or DAOs to more lightweight form that is more convenient for presentation
  • applying security checks
  • managing transactions
Service
Entity
Command
DAO

Because Facade does not depend on any particular view it can be reused by several different Controllers. This is especially convenient in situations where UI layout requires that some panels (e.g search box) are displayed on multiple pages. However the mapping between Facade and Controller is not 1-n but most likely n-n as one Controller can use mutiple different Facades (e.g one for handling view's main functionality and one for handling additional panels).

At first Facade may seem quite similar to Service of domain layer but there are some important differences. Not like Service a Facade can depend on Command. That makes sense cause Command is actually the DTO between presentation and application layer. Facade should however not in any case depend on HTTP or any other presentation layer technology. Secondly Facade handles application specific workflow whereas Service in domain layer models processes in domain. Actually Facades can make separate Service layer (not Services themselves) redundant. But that is already another topic .

References

Most of the patterns and concepts described are taken either from Fowler especially Patterns of Enterprice Architecture and Evans Domain-Driven Development (there is also free summary ebook version).

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.