Case Study: Usable and Unusable APIs
It was the best of times, it was the worst of times…
It was the age of wisdom, it was the season of light. A great library called dom4j was written with its users in mind. It included a quick start guide and a cookbook for people that actually wanted to get things done. Converting a document to a String took 15 characters: document.asXML(). But there were too many competing XML parsing implementations, so a standard was created. And sadly, dom4j has not been updated to adhere to that standard.
It was the age of foolishness, it was the epoch of incredulity. 15 characters to turn a document into a string? That is far too few. What will we tell our managers when they ask how many lines of code we have written? We have a better way and it is called Xerces:
import java.io.StringWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Node;
public final class XmlUtil {
private static final TransformerFactory factory = TransformerFactory.newInstance();
public static String toString(Node node) {
if (node == null) {
return null;
}
try {
Source source = new DOMSource(node);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
return stringWriter.getBuffer().toString();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
}
People have been using dom4j and jdom for years… The only reasons for which people use JDK libraries(XML) is because:
– They don’t want to add new dependencies
– They are doing something trivial
– They already have lots of utility classes in their code base
Somewhere along the way, the Java “aesthetic” for coding became bend towards the noisy and overcomplicated. I tend to think it’s a combination of the earlier brute force movements towards real-world objects, useless flexibility and the desire to just get it done first, and then think about it later. However it came about, it generally seems wise in most applications to cover over many of these libraries carefully, rather than to allow their pathologies to percolate upwards. If the foundation is a mess, it always demands extra effort to keep that from infecting the rest of the structure.
Paul.
Thank you for this article
Sad but true 🙁
good article,thank you
I m all right with you…