java extend or wrap a class to add extra functionality
Asked Answered
P

6

7

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?

Pasho answered 27/1, 2010 at 21:11 Comment(0)
B
4
  • 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 ?
Bartley answered 27/1, 2010 at 21:19 Comment(0)
A
10

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.

Archimandrite answered 27/1, 2010 at 21:16 Comment(0)
B
4
  • 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 ?
Bartley answered 27/1, 2010 at 21:19 Comment(0)
O
3

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.

Oby answered 27/1, 2010 at 21:15 Comment(0)
K
1

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.

Kristoforo answered 27/1, 2010 at 21:15 Comment(0)
F
0

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.

Fite answered 27/1, 2010 at 21:26 Comment(0)
D
0

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).

Duotone answered 27/1, 2010 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.