views:

147

answers:

6

When you want to add some extra information into a class, what way would you prefer: would you extend that class or make a wrapper around it?

In my particular scenario, I want to add some pagination information with a List that I get from database. That pagination information will include:

int currentPage;
int totalResults;
int containedResultsIndex;
int totalcontainedResults;

and a couple of methods:

Boolean isNextPageAvailable();
Boolean isPrevPageAvailable();

Whats your opinion, extend or wrap?

+2  A: 

Too much extends is evil, and will make your code difficult to read/understand go with composition, just create a new class that has a Collection and your extra members needed for pagination.

Omar Al Kababji
+1  A: 

I prefer to wrap where possible. Especially in your List example - the wrapper class can contain any list type, whereas a extended class is tied to a specific concrete superclass.

developmentalinsanity
+5  A: 

It sounds like you're asking whether you should favor inheritance or composition in your situation. I would say that you are not creating a new implementation of List and you don't really care how List is implemented, so inheritance doesn't fit your problem. Instead, you're providing paging functionality. I would create a class that generically wraps up (encapsulates) the paging logic using List or some other generic collection.

Jonathon
+3  A: 
  • in your case wrap the existing List and make your class implement List itself, delegating all methods the the original list (which is passed in constructor, for example)
  • inheritance isn't always wrong, but in this case you won't know what class to extend - will it be ArrayList, or LinkedList ?
Bozho
A: 

Even if you extend, you will not be able to call the new methods through the super class reference. It is best to just wrap it.

fastcodejava
A: 

Having an elegant PagingList (extending List) is an adequate approach.

  • Why delegating when you can inherit the stuff you need?

  • It's like the relationship between FileReader and BufferedFileReader ( And nobody would say that's bad practice).

stacker