All 1 entries tagged Views
View all 3 entries tagged Views on Warwick Blogs | View entries tagged Views at Technorati | There are no images tagged Views on this blog
September 23, 2005
MVC Views; how stupid should they be
It seems to me that a lot of people are not utilising the full power of the "view" concept of the MVC paradigm.
For example, imagine a scenario where you want to render one page for logged in users or another for logged out users. Should this logic go in the controller, or the view? It seems the gut reaction is to put it into the controller, which I think is wrong :)
Controllers should be doing business logic, with complete disregard for how it is rendered. Controllers should not know whether they are returning html, rss etc. Of course this is naieve and it may well be that different models are required, in which case the controller has to know, but in the main, keep those MVC boundaries!
In the readonly/readwrite view example, I typically have a delegating view:
public final class PagePermissionsView implements View {
private View readView;
private View editView;
public void render(
final Map model,
final HttpServletRequest request,
final HttpServletResponse response) throws Exception {
ServletRequestAttributeAccessor accessor = new
boolean userLoggedIn = ….
if (userLoggedIn) {
editView.render(model, request, response);
} else {
readView.render(model, request, response);
}
}
public void setEditView(final View detailsView) {
this.editView = detailsView;
}
public void setReadView(final View simpleView) {
this.readView = simpleView;
}
}
This keeps view related logic firmly in the view.
Same with complicated reports. If you need to group data, a lot of developers will perform that grouping in the controller. I would rather do that in the jsp and utilise tag libraries to perform the data, for example, I very often have need of a tag which will take in a collection and return a map, where the key is the value of a property, and the value in the map is a collection of all the objects that matched.
I know exactly why developers are "afraid" to put logic into views, and that is because of the horror that was pre MVC :) But there is a difference between business logic and view logic.
A useful yardstick for any "where should this go" question is "if I need to change how this works, which layers would I need to change". If I decide to change how the view is rendered, I want to change the view, not the controller :)
Rant over; let the flames being…..