Reputation: 10425
At the end of a controller request method, we usually do something like :
modelAndView.setViewName("welcomePage");
return modelAndView;
or
return "welcomePage";
Despite this way being simple and efficient, am I the only one to find these "magic strings" wrong ?
The same "welcomePage" string could be used several times in the same class or in other classes, thus breaking the "Don't repeat yourself" principle. Moreover, if I happened to rename "welcomePage.jsp", I would have to replace en masse all the occurences of "welcomePage" in the project.
The first solution that comes in mind would be to transform these (possibly shared) strings into (possibly centralized) constants or enumerations. But I am not sure this is the way to go with Spring MVC.
What do you think about these kind of "magic strings" ? Does Spring MVC allow to return views in a neater way ? If not, what solution would you recommend ?
Upvotes: 1
Views: 974
Reputation: 47994
1) I got over it when I realized my aversion to strings in code was based on things I learned by rote as an undergrad from people for whom EMACS was the pinnacle of all IDEs. Is AppConstants.ViewNames.WELCOME_PAGE really better than "welcomePage"? It is obvious in intent and easy to understand. Most of the time when I see people insist every string ever used more than once be a constant, the constant names are so close to the string names so that the code makes sense, that if you did change the, it wouldn't make any sense unless you change the constant name too anyway. /rantoff Changing it takes 15 seconds in a modern IDE.
2) The view resolver can automatically render /welcomePage.htm with WEB-INF/jsp/welcomePage.jsp (or whatever you set up). There is no reason to specify a view specifically by name unless you want to render a JSP whose name does not match the html doc requested in the URL path.
3) structure your pages so as to take advantage of #2 above and not need to specify explicit view names.
Upvotes: 1