开发者

java extend or wrap a class to add extra functionality

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?


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.


  • 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 ?


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜