First ICollection implementation: Array Collection


Wrote my first concrete implementation of my ArrayCollection class:



namespace Testing.Collections


{


    using System;


 


    public class ArrayCollection<A> : ICollection<A>


    {


        private A[] array;


        private int count;


 


        public ArrayCollection() {


            array = new A[0];


            count = 0;


        }


 


        public virtual bool Empty {


            get {


                return count == 0;


            }


        }


 


        public virtual bool Add(A element) {


            //From CLR 369 (Dynamic Tables)


            if (array.Length == 0) {


                array = new A[1];


            } 


 


            if (count == array.Length) {


                A[] doubledArray = new A[count * 2];


                Array.Copy(array, doubledArray, count);


                array = doubledArray;


            }


 


            array[count] = element;


            count++;


 


            //Adding an element always modifies an ArrayCollection


            return true;


        }


    }


}


Now i just need to test it.  I’m using the CLR pseudo-code translated into C# for this algorithm.


I can already smell a refactoring coming in with the constructor.  “Introduce explaining variable” for the hardcoded in 0 (in the array constructor), and the “Promote Local to Argument” so that i have a constructor that takes in an initial capacity.  The count = 0 could go into the class body, or could just be avoiaded alltogether.  I’m not sure which is nicer, field initialization in the class body, field initialization in the constructor, or no field initialization when it keeps its default value.


However, I’m not touching this until it’s passed my tests.  Must resist the urge to code like mad.


Comments (3)

  1. Cool. It’s good for beginners to see the process of writing/designing code as well as more advanced coders to refresh/think. I especially like the references to the refactoring patterns.

    It’d be nice if you replaced the "Refactoring Pattern References" with links 😉