views:

68

answers:

2

The situation occurs when getting some data from the database to compose a report that is grouped by various fields. For example, grouped by month, then type and then actual vs prediction. The database query returns simply a List< Object[] >. But it is boring to directly render it as an HTML table. What I do is to group the data inside a Map<Integer, Map<String, Map<Type, Integer>>>. It can be done in a straightforward way and if I use TreeMap's, the data is automatically sorted for me. The resulting JSP code is much simpler.

Is there any problem with this approach? (memory, speed, or something else?)

+2  A: 

The HTML renderer shouldn't have to know the implementation details of you DAO.

I think for you DAO that returning List<Object[]> is more simple than returning Map<Integer, Map<String, Map<Type, Integer>>>. Every class interface should be easy to understand, so I would use List<Object[]>.

If it's more straightforward to render the HTML table using Map<Integer, Map<String, Map<Type, Integer>>> maybe is better to create a method to convert List<Object[]> to Map<Integer, Map<String, Map<Type, Integer>>>.

This way you keep your UI detached from your database classes.

You also asked about memory and speed. I think the best approach is to test both situations and use a profiler to measure if this is really an issue.

Daniel Moura
I guess the GUI should receive a very simple data structure, in the sense it should be easy to use/understand. This keeps the page clean and editable by web designers who don't program (think about three nested <c:forEach>s versus one single <c:forEach> with lots of flags and conditionals). Maybe it's not wise to give the DAO the responsibility of grouping and sorting its output. I guess I'll let the managed beans/controllers do the job. Thus, I'll have the flexibility to group and sort the DAO's output in various ways.
Bráulio Bezerra
+1  A: 

Is there any problem with this approach? (memory, speed, or something else?)

A TreeMap will use more memory than ArrayList, and probably than a LinkedList. It might be slower ... or faster ... depending on exactly how the lists are sorted and used.

But the chances are that the difference won't be noticeable unless the data structures are really big. The best approach is to start with whichever data structure gives you the simplest and most robust code. If (and only if) performance is noticeably slow should you spend time optimizing, and then only if profiling tells you that this is the cause of your performance issues.

Stephen C