Despite being the clever Java coder I am, I noticed I know way too little about various design patterns. The builder pattern caught my eye as something to learn, as I have certainly seen my fair share of telescopic constructors already.
So, I decided to give it a try. The following is a really simple class represents a cell in a table of data. So far a cell can have text (its contents) and a URL (if it is to be rendered as a hyperlink), but I could see myself adding other parameters as well, so there's an inner static class called CellBuilder
as well.
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A class that represents data in a table cell.
*/
public class CellData {
/** The text that's displayed in the cell. **/
private final String text;
/** The URL to which the text should link to, if any. **/
private final URL url;
private CellData(CellBuilder builder) {
this.text = builder.text;
this.url = builder.url;
}
public String getText() {
return text;
}
public URL getUrl() {
return url;
}
/** A builder to avoid telescopic constructors. **/
public static class CellBuilder {
private String text = "";
private URL url = null;
public CellBuilder text(String text) {
this.text = text;
return this;
}
public CellBuilder url(String url) {
try {
this.url = new URL(url);
} catch (MalformedURLException ex) {
Logger.getLogger(CellData.class.getName()).log(Level.SEVERE, null, ex);
}
return this;
}
public CellData build() {
return new CellData(this);
}
}
}
A new cell would then be created, for example, like this:
CellData cell = new CellData.CellBuilder().text("hello").url("http://www.example.com/foo").build();
Now, I don't know about you, but to me that doesn't look much more easier or cleaner than doing it the traditional way, by passing those arguments to the cell in its constructor. :( Yet another way would be to do it like this:
CellData cell = new CellData();
cell.setText("hello");
cell.setUrl("http://www.example.com/foo");
Why shouldn't I do it like that either? I wonder if this particular use case is still too simple to get the best out of this design pattern, or if I'm doing something else completely wrong?
Notice that this doesn't strictly conform to the architecture presented in Wikipedia, but that's because I read about this way from some other source where it was more like this, and the Wikipedia way with about five classes felt like too complicated for a simple matter like this.