Saturday, June 17, 2017

C# Enumerator

Recently when I was writing a function, it has for-each loop and if it's odd iteration result should be multiply by 1, if it's even it should be multiply by 3.

So our my mind default going to keep a one bool variable to check iteration is odd or even. This is not object oriented way of programming. When new requirements comes this has lot of changes. So I have though of use C# strong language features in order write my code more OO way.

So I have used IEnumerable, Have look at MulitplyingFactors function which has replaced the bool variable and that method is  extendable. I have removed tight couple IsOdd variable to separate function

Before
        static void Main(string[] args) {
            IEnumerable<int> list = new int[] { 2, 4, 5, 8, 1, 2, 8, 9 };
            Console.Out.WriteLine(GetValue(list));
            Console.ReadLine();
        }

        static int GetValue(IEnumerable<int> list) {
            int result=0;
            bool isOdd = false;

            foreach (int item in list) {
                factor.MoveNext();
                if(isOdd )
                      result += item;
                else
                      result += item *3;

                isOdd = !isOdd ;
            }
            return result;
        }

After
        static void Main(string[] args) {
            IEnumerable<int> list = new int[] { 2, 4, 5, 8, 1, 2, 8, 9 };
            Console.Out.WriteLine(GetValue(list));
            Console.ReadLine();
        }

        static int GetValue(IEnumerable<int> list) {
            int result=0;
            IEnumerator<int> factor = MulitplyingFactors.GetEnumerator();

            foreach (int item in list) {
                factor.MoveNext();
                result += item* factor.Current;
            }
            return result;
        }

        static IEnumerable<int> MulitplyingFactors {
            get
            {
                int factor = 3;
                while (true) {
                    yield return factor;
                    factor = 4 - factor;
                }
            }
        }


No comments:

Post a Comment