Here’s an example — I want to implement a DropoutStack (a stack with a fixed max size, and will remove the elements from bottom when it is oversized) based on the existing LinkedList in C#. (This is where the idea came from: Limit the size of a generic collection? ) However, there are at least two ways to implement.
1) The New Data Structure (DropOutStack) is inherited from the Existing Data Structure (LinkedList). Just like the answer.
public class LimitedSizeStack<T> : LinkedList<T> { private readonly int _maxSize; public LimitedSizeStack(int maxSize) { _maxSize = maxSize; } public void Push(T item) { this.AddFirst(item); if(this.Count > _maxSize) this.RemoveLast(); } public T Pop() { var item = this.First.Value; this.RemoveFirst(); return item; } }
2) The New Data Structure owns the Existing one. Something like:
public class LimitedSizeStack<T>
{
private readonly int _maxSize;
private LinkedList<T> _list;
public LimitedSizeStack(int maxSize)
{
_maxSize = maxSize;
_list = new LinkedList<T>();
}
public void Push(T item)
{
_list.AddFirst(item);
if(_list.Count > _maxSize)
_list.RemoveLast();
}
public T Pop()
{
var item = _list.First.Value;
_list.RemoveFirst();
return item;
}
There are pros & cons for both methods.
For 1: we do not need to care about implementing the common methods such as Clear() and Count; but other methods which is not related to DropOutStack will also be exposed (e.g., Find(), AddBefore()).
For 2: that's the opposite. Unrelated methods are hidden, but we need to reimplement the common methods.
My question is:
1) Is there any convention of implementation, i.e., is it always better to choose one option?
2) Is there any other factors we need to consider (e.g., for efficiency and memory) when making the decision?