Extension method

All posts tagged Extension method

Dear Reader,

Today i had to do some unit testing of a class which had some private instance and static methods along with non privates in it. These methods had some good core logic in it which i determined to do unit testing. Though many articles and experts say that its ok not to do so for a private method,  but i wanted my logic to be fail proof. Hence only way to do this is to use reflection APIs to access the private members.

Below is the simulated code (for article sake) shown which needs to be tested:

class ToBeUnitTested
    {
        private void PrivateMethod()
        {
            //Some business code logic
        }

        private static void StaticMethod()
        {
            //Some business code logic
        }
    }

So, i started to write the unit testing code which had the reflection APIs to invoke these members. Instead of embedding the reflection code in my unit test class, i refactored it to a helper class as shown below:

class Helper
    {
        private Helper() { }

        public static void InvokePrivateMethod(Type type,
            string methodName, object instance, object[] parameters)
        {
            BindingFlags flags = BindingFlags.Instance | 
                BindingFlags.InvokeMethod | BindingFlags.NonPublic;

            RunMethod(type, methodName, instance, parameters, flags);
        }

        public static void InvokePrivateStaticMethod(Type type,
            string methodName, object[] parameters)
        {
            BindingFlags flags = BindingFlags.InvokeMethod |
                BindingFlags.NonPublic | BindingFlags.Static;
            RunMethod(type, methodName, null, parameters, flags);
        }        private static void RunMethod(Type type, string methodName, 
            object instance, object[] parameters, BindingFlags flags)
        {
            //Reflection code
        }
    }

As shown above code, i have couple of public helper methods for private instance and private static. Of course i had couple more for protected , etc. But shown only 2 for simplicity sake. As you can see in the above code, i have more methods for each of the method with different access modifiers in my testable class. I some how did not like the way it is done above. I just wanted the helper class to be simple and concise with only one method rather than 3 methods. The only changing thing is the BindingFlags combination. So i decided to do a bit of refactoring and having only single method RunMethod(….) in the helper class which is very simple and understandable for Helper class.

To do this refactoring, i though of using Enum to specify combination choice for PrivateInstance and PrivateStatic, etc. But BindingFlags is already an Enum. So Enum for Enum is not a good choice and makes it more difficult to understand. Hence the next thing occurred to me was to use Extension methods with Enum. I really like how the Extension method offers a great deal of flexibility and maintainability of the code.
Below is the refactored code:

public static class BindingFlagsExtension
    {
        public static BindingFlags GetInstancePrivateMethodFlags(this BindingFlags flags)
        {
            return BindingFlags.Instance |
                BindingFlags.InvokeMethod | BindingFlags.NonPublic;
        }

        public static BindingFlags GetStaticPrivateMethodFlags(this BindingFlags flags)
        {
            return BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static;
        }
    }

    class Helper
    {
        private Helper() { }        public static void InvokeMethod(Type type, string methodName,
            object instance, object[] parameters,BindingFlags flags)
        {
            //Invoke reflection code
        }
    }

Now the helper class became very simple and very concise too, even Helper class adheres much more towards SOC principle. Even maintaining and extension of the code (SOLID principle) for Helper and Extension class is high.

In fact i feel good that i did some thing cool today, though its not amazing one. Love to hear suggestions. So please feel free to comment on other ways of improvement.

Thanks & Happy Coding,
Zen :)

Dear Reader,

Today i learn something interesting and quite effective with the C# feature extension methods along with enums. There are at times we need to do some extensible operations on enums. Unlike structs/classes, enums do not provide us any space in itself to add Methods for doing some operations on it or its data members.

Yes there is always a crude way of doing this without using of extension methods at all. But think about maintainability of your code. What if this code chunk (operation) needs to be reused at multiple places in your code. Yes we could push the code chunk to a method and then to a reusable class. Though this is half way approach, extension methods do provide us a near approach in fact.

This is why it’s quite interesting to me and i always admire and look for places to use this feature only if it is justifiable. So below is one similar chunk of code which i came up with (not the real exact code) but i  do believe it does represents the intent meaning.

 public enum WorkingDays
    {
        Monday,
        Tuesday,
        Wednesday,
        Thurday
    }

    public static class DaysOfWeekEnumExtension
    {
        public static bool IsWorkingDay(this WorkingDays workingDay, string currentDate)
        {
            bool result = false;
            if(string.IsNullOrWhiteSpace(currentDate))
                result = false;
            else result = Enum.IsDefined(typeof(WorkingDays),currentDate);

            return result;
        }
    }    

   public partial class Program
    {
         public static void Main()
        {
            WorkingDays workDays = default(WorkingDays);//Assume this value comes from a remote service
            DateTime dt = DateTime.Now;
            dt = dt.AddYears(1).AddMonths(5);
            Console.WriteLine("Some day : " + dt.DayOfWeek.ToString() + " to be checked as working day " +
                " =>" + workDays.IsWorkingDay(dt.DayOfWeek.ToString()));
            Console.ReadKey();
        }
    }

As you can see, in the main method, the interface for using this extension along with the enum i have defined became very simpler and cleaner. The reason i have used default() keyword instead of directly assigning one of the member of Enum because i assumed that i may not know what should be the default value. It could be any thing from the enum members. So i have left the default() to choose. In real world, assume i may get the values from a remote service or a web service perhaps.

I am sure there are many more great examples than above. I would be happy to learn them. So please do a comment.

Thanks and Happy Coding,
Zenwalker :)