3

In my DAO classes, I return a list of entities.

Would you recommend I use a List<T> like:

List<User> findAllUsers(...);

In my db calls, I want to wrap the collection and createa a ResultList<T> that inherits List<T> (or whatever generic collection you recommend I use) and add some properties to it, how would I do that?

public class ResultList<T> extends List<T> {
   private int SomeThing;

   // getter/setter
}

Is this (above) the best way?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

4 Answers4

3

I wouldn't necessarily extend List<T>, but rather hold onto an instance of List<T>, as I prefer delegation over inheritance.

public class ResultList<T> {
    private List<T> backingList;
    private int SomeThing;

    // getter/setter
}

From here, you can define your own methods that delegate to the backing list.

Really though, what you have should work just fine for what you are trying to do. It may just make it a bit harder to change in the future.

Community
  • 1
  • 1
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
1

Returning a generalized list is standard practice for DAO's. As for the second part of your question, I would recommend just returning a List and then defining a copy constructor on your ResultList that accepts a generic list as argument. Which is a clean and extensible solution, assuming of course your ResultList instances do not need information only available within the scope of the DAO method call.

List<User> data = userDao.findAll();
ResultList<User> results = new ResultList<User>(data);
Perception
  • 79,279
  • 19
  • 185
  • 195
1

List is an interface, not a class, so you would be implementing a class with a List interface.

If you want to add extra properties then should probably extend the List interface first, then implement it.

public class ResultList<T> extends List<T> {
   // getter/setter declarations
}

public class ResultListImpl<T> implements ResultList<T> {
   private int SomeThing;

   // getter/setter implementations
}
tjdett
  • 1,703
  • 1
  • 18
  • 23
1

I don't see any issue with what you've got there. You could argue for composition over inheritance (as I've done here), but it comes down to personal preference. Do your Entities all inherit from a common superclass? You could then make it a bit more specific

public class ResultList<T extends BaseEntity> {
 private List<T extends BaseEntity> list;       
 private int SomeThing;

}
Peter
  • 29,498
  • 21
  • 89
  • 122