Clean Code Tip #7 – Method Purpose

#7:  Methods should either do something or decide something, but not both.

For example, the method below has a method GetDistinctArrarCount that returns an array count and it removes empty elements.  The removal elements should be done separately since the method purpose is to get the array count.

static void Main(string[] args)
        {
            List<string>  people = new List<string>() { "Brian", "Sara", "", "Bob"};

            int count = GetDistinctArrayCount(people);

            Console.Write(count);
            Console.ReadLine();
        }

        private static int GetDistinctArrayCount(IEnumerable<string> arrayValues)
        {
            // Remove Emtpy Values
            arrayValues = arrayValues.Where(x => !String.IsNullOrEmpty(x));

            // Return Distinct Count
            return arrayValues.Distinct().Count();
        }

Here’s a better way to write this:

 static void Main(string[] args)
        {
            List<string>  people = new List<string>() { "Brian", "Sara", "", "Bob"};

            // Remove empty elements before getting the distinct count
            people = people.Where(x => !String.IsNullOrEmpty(x)).ToList();
            int count = GetDistinctArrayCount(people);

            Console.Write(count);
            Console.ReadLine();
        }

        private static int GetDistinctArrayCount(IEnumerable<string> arrayValues)
        {
            // Return Distinct Count
            return arrayValues.Distinct().Count();
        }
Advertisements

About Brian McKay
Software Architect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: