Dry your view using refactor and conventions

DRY is a concept applied quite broadly in code. In a web application it's also important to extrapolate its use to the view layer (MVC) in order to increase clarity and consistency.

At the end of this post I'll explain how a user story that had to be delivered became much easier to implement because we had a dry and refactored view.


Concrete example of a view pattern being refactored and dryed

As I usually try to explain things by example, I'll show a JSP that can be refactored and dried. Please notice that the idea of refactoring and drying your view using conventions is technology agnostic and can be achieved with other languages and frameworks as well.

Let's say we have to implement this form:


The example below shows one way of implementing the aforementioned form using Spring MVC JSP tags.


The convention used was that the default label will be label.${id}.

Tag Files and Conventions
If you want to know how to create your own JSP 2.0 tag file, like the one created above (form-ext:inputText), here are a few tutorials.
But always remember about the conventions over configurations.

Here is the file that was used to implement form-ext:inputText:

You can download it if you want: inputText.tag


If the user of the tag (inputText.tag) still wants to send the parameters label, size and maxlength, they would be able to do so. They are not required and have default values, though.

Basically if you apply these two concepts (Tag Files and Conventions) you can dry your JSP's... But you have to identify the duplication patterns.


Extract Tag File - A view refactor similar to Extract Method

What was shown above is a step by step of a refactor that I call Extract Tag File. It's quite similar to extracting a method, but instead of code, we have JSP.
I wish the IDEs had this refactor implemented ... Who knows someday... Or maybe we could write a plug-in for Eclipse or IntelliJ.

How we applied this on a real project to deliver business value quickly

Recently, on my current project, we had to change the way the error messages were shown to the user. They had to be field context aware, which means that if there was an error related to the field "Given Name", the error message had to be show next to the field.

This is what we had before:


This is what we had to implement:


Can you imagine how much easier it was just because we had our DRY VIEW? Our fields were wrapped and, therefore, it was just a matter of implementing this inside the tag file...

That's what we aim... Deliver business value quickly!!! Happy client... Happy developers...

Share this story