CREATE XMLWRITERS FOR BUSINESS OBJECTS
You need to output XML data, but the procedural nature of the code
seems
wrong. While it's possible to automatically turn a business object into
XML via reflection, issues like dates and custom formatting will
quickly
complicate any but the most complex designs.
The simplest choice is to just make a toXml( ) method on each business
object. Each business object will then either print out its attributes
or,
if that attribute is another business object, call its toXml( ) method.
This allows the XML printing code to have access to the object's
private
fields.
The method looks something like this:
public String toXml( ) {
StringBuffer buffer = new StringBuffer( );
buffer.append("");
return buffer.toString();
}
However, toXml() is a poor solution in two ways. First, it assumes that
the XML data should be created as a String. With a large series of
business objects, it creates a lot of Strings in memory and hinders
performance. Instead, it's better to write the XML directly to a
Writer, but it
requires that an IOException is thrown. For example:
public void toXml(Writer writer) throws IOException {
writer.write("");
}
The second reason why toXml() is a poor solution is because knowing how
to output itself is not the job of a business object. There should be
an
object that specializes in that job, such as:
public interface PersonWriter {
public void write(Person person, Writer writer) throws IOException;
}
public class XmlPersonWriter implements PersonWriter {
public void write(Person person, Writer writer) throws IOException
{
writer.write("");
}
}
While this new system no longer has access to the Person's private
variables, it's far more usable in an object-oriented system. Code can
be
written, which takes a PersonWriter, and then given an XmlPersonWriter
or a
FilePersonWriter. In addition, an XmlCompanyWriter can reuse
XmlPersonWriter to output each person working for it. If you create
classes that have
one job--one thing to do--the code will be more usable and stable.
----------------------------------------