Why do Queue(T) and Stack(T) not implement ICollection(T)?

后端 未结 3 1098
眼角桃花
眼角桃花 2021-02-01 07:54

Before I even ask, let me get the obvious answer out of the way: The ICollection interface includes a Remove method to remove an arbitrary

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 08:29

    I can't give the "what was the actual thinking" answer - perhaps one of the designers will give us the real thinkng and I can delete this.

    However, putting myself in the mindset of "what if someone came to me to make this decision", I can think of an answer.. let me illustrate with this code:

    public void SomeMethod( ICollection collection, T valueA, T valueB)
    {
    
      collection.Add( valueA);
      collection.Add( valueB);
    
      if( someComplicatedCondition())
      {
        collection.Remove(valueA);
      }
    }
    

    (Sure, anyone can create a bad implementation of ICollection, but we expect the framework to set the example). Let's assume Stack/Queue implement as you state in the question. So is the code above right, or does it have edge case bugs because ICollection.Remove() should be checked? If valueA MUST be removed, how do I fix this to work with both Stack and Queue? There are answers, but obviously the code above is wrong in this case - even though it smells reasonable.

    So both interpretations are valid, but I'm good with the decision made here - if I had the code above and knew I could be passed a Queue or Stack that I could design around it, but it sure would be an easy bug pit to fall into (everywhere you see ICollection, remember the edge cases for remove!)

提交回复
热议问题