I've provided only simplified code as it's more of an abstract design question.
So I have many, many nested business/domain event objects, e.g.
public class Event
{
//bunch of properties and standard accessors
}
public class ExplosionEvent extends Event
{
//properties and standard accessors
}
And many more of these at different levels. If I need information about any given object chosen, I display it in HTML like so
private String generateHTML(Event event)
{
StringBuilder sb = new StringBuilder();
sb.append("<HTML><table>");//simplified
sb.append("<TH>Time</TH>");
sb.append("<TD>" + event.getEventTime() + "</TD>");
if (event instanceof ExplosionEvent)
{
//append HTML and ExplosionEvent specific data
}
// ...many, many more calls like the one above
sb.append("</table></HTML>");
}
As I have many event types, this means loads of duplicated HTML table tags and uses of instanceof
so generateHTML
is hundreds of lines long, split into methods of course but still, it's a lot of code that makes this hard to understand, navigate and therefore maintain.
This is ugly and I need a better design for this. I had the idea of creating a method on Event
which is overridable by all sub methods
//Using LinkedHashMap to preserve order as Properties wont do that
public LinkedHashMap<String, String> getAttributes()
{
LinkedHashMap<String, String> list = new LinkedHashMap<String, String>();
list.put("Time", eventTime);
}
sub-classes then override this, call their parent and add date specific to them to the list meaning that no matter how many Event
classes there is, the existing generateHTML
method (external to Event
objects) will then simply be one small loop
private String generateHTML(Event event)
{
StringBuilder sb = new StringBuilder();
b.append("<HTML><table>");
for (Entry<String,String> entry : event.getAttributes().entrySet())
{
sb.append("<TH>" + entry.getKey() + "</TH>");
sb.append("<TD>" + entry.getValue() + "</TD>");
}
sb.append("</table></HTML>");
}
Is this putting too much logic in business/domain objects?
Is there a better way?