5

I want to write a Bounded Priority Queue class. This is essentially a priority queue but has a bound on the number of elements that can be there in the queue. So, if I insert a new element and the queue is full, then I see if the element is greater than the top of the queue. If yes, then I discard the new element. If no, then I remove the top element and insert this new element (and the queue gets automatically reorganized). I have currently implemented BoundedPriorityQueue as derived from PriorityQueue having a "maxCount" member and I have overridden the add method and added the functionality I described above. I am wondering if I should consider doing it the composition way rather than the inheritance way. My current approach seems simple though.

If I were to go for composition, then I have to derive from the AbstractQueue class, implement the methods and then compose the priority queue with it.

Thanks,

Venk

Venk K
  • 1,157
  • 5
  • 14
  • 25
  • 2
    Is there some reason you don't like your current solution? Is it overly complex? Is it hard to understand? Is it too slow or prone to race conditions? – Lee Meador Oct 16 '13 at 17:59
  • well, none of it. But in Effective Java, Joshua came across a slightly different but related problem but solved it using composition. I am trying to explore the reason behind it. – Venk K Oct 16 '13 at 19:09
  • 1
    If you use inheritance you have to ask yourself if you could substitute a Priority Queue with a BoundedPriorityQueue without facing any problems. If yes use inheritance, otherwise composition. If in doubt, use composition. – helpermethod Aug 22 '14 at 10:10

2 Answers2

1

in my opinion it is better to use composition. because, inheritance this way is the violation of Liskov substitution principle. derived types shouldn't replace base types' functionality. this link will be useful: prefer composition over inheritance

Community
  • 1
  • 1
irakli2692
  • 127
  • 2
  • 9
0

I would go with inheritance in the described case - it's a typical example. You can (as I do when I cannot decide between multiple implementations) create both solutions, try them out, see how they look API wise, performance, implementation and comprehension wise, and decide based on that.

alterfox
  • 1,675
  • 3
  • 22
  • 37