I believe, all the published coding methodologies, practices and guidelines strive to achieve one simple thing: I said it - Simplicity - making things simple, easier to understand, easier to maintain. Refactoring, is one such practice, which we all might have been doing for ages, perhaps without knowing that the practice is labeled 'Refactoring'. By definition, Refactoring is all about changing the structure of code without changing its expected behavior. Why do it - to simplify, simply put.
There are many refactoring techniques one might want to use with respect to object oriented programming. I wouldn't enunciate all of them here; I would recommend Martin Fowler's most excellent book for the same. Consider one such common technique - Rename. As benign as this might appear, Renaming is one of the most powerful steps towards simplicity. Be it a member variable, a formal parameter, a method name or the class name, proper (re)naming should portray the true intent and eliminate the need for comments. Another common technique is Extract Method. More often than not, a method gets bulky and its real intent starts becoming hazy. At such times, you may want to break it up into smaller methods so that the code becomes more 'readable' and hence maintainable.
Now, the techniques that I have just mentioned require some amount of manual effort in the code editor (IDE). For instance, changing the name of a member variable would mean changing them in all class methods where it is used. These changes could be drastic, if the members/methods are public. Manual effort is but, error prone and typically, refactoring entails unit tests to certify that expected behavior is not violated. To that end, wouldn't it be great to have a tool of sorts which automates most of such common refactoring techniques? VS.NET is a far cry in this respect; so, ReSharper comes to the rescue!
Well actually, the very purpose of this blog post was to share with you, my experiences of working with this fabulous tool. ReSharper is essentially, a refactoring tool that comes as an add-on to the VC# IDE provided by VS.NET 2003. In addition to facilitating some refactoring techniques, ReSharper provides enhanced navigation, formatting and intellisense enhancements over and above what VS.NET provides, which make C# development even more pleasurable. There is good reason to see why VS 2005 provides most, if not all of what ReSharper provides already.
Well yes, as the name would suggest, ReSharper is a tool that works only with C#. I don’t want to get too philosophical here, but it seems as if VB.NET was perhaps, alienated from ReSharper for the same reason why Refactoring (or most of it) was opted out of VB 2005. (Ofcourse, time and scope, among many other things could have been a reason). In my opinion, refactoring is a technique that cuts across all languages and has to be adopted (I must say religiously) by all programmers, whatever be their language of choice for development. I am also of the opinion that IDEs have to provide refactoring support in some form or the other.
Nonetheless, ReSharper has been one of the best developer tools I have ever worked with. It is truly a developer productivity enhancer and I personally would recommend ReSharper for every C# developer working on VS.NET 2003. Its more than worth 149$; go get your copy today. With ReSharper, refactoring is fun too !
Strategy
is a quite frequently used pattern. Strategy pattern involves "defining a family of algorithms, encapsulating each one, and making them interchangeable. Strategy lets the algorithm vary independently from clients that use it."
Essentially strategy entails creating an abstract class or an interface abstracting the family of algorithms to be used. I must say that there are umpteen applications of this pattern within the BCL. Let's examine one of them here:
IComparer is an interface defined in the System.Collections namespace and defines a method that can compare two objects. It's primary purpose is to provide a way to customize the sort order of a collection, which is required in the Array.Sort and Array.BinarySearch method implementations. So mapping this to the Strategy (refer to the link above for the class diagram of the pattern):
Icomparer Interface : Strategy, Array class : Context
On similar lines, another citation would be IListSource / IList, which is used in data binding in Webforms/Windows forms.
I will leave it as an exercise to the adept .NET Fx developer to just add plenty more to this list!
Of late, I am getting more and more interested in Design Patterns. As Allan Shalloway, in his most excellent book, Design Patterns Explained explains, design patterns are a great way to understand Object Oriented Programming better. Though design patterns are not restricted to the seminal work from the GOF, they do provide a solid basis on how patterns, in general are conceived. I understand that there are umpteen books and resources on patterns, especially those in C# and VB.NET. What I am trying to do here try to cite certain patterns that exist with the BCL, albeit not clearly visible, and also reflect certain problem-solution pairs that we are all way too familiar with, but don’t classify them as patterns. Let me start with an interesting problem we face quite often:
You need to execute a method asynchronously. Now, the Thread and the ThreadPool class allow you to do that, but there is a catch. They accept only specific types of delegates - ThreadStart and WaitCallback respectively. Therefore, you cannot asynchronously call methods with arbitrary signatures directly. So, what's the solution? The answer is Command Pattern. Essentially, in this pattern, you encapsulate the command/operation to be executed as an object, with the method parameters represented by the state of command object. So, to apply the command pattern to our problem, we would need to create a command class that can execute any method, irrespective of the signature. The best way to handle this is by using Delegate.DynamicInvoke method. Therefore, the state of our Command object would contain a delegate instance and an object array, which is passed to the DynamicInvoke method and also, optionally, a result object. Here's how:
public class Command
{
private readonly Delegate _target;
private readonly object[] _args;
private object _result;
public Command(Delegate d, object[] args)
{
_target = d;
_args = args;
}
public void InvokeCommand()
{
_result = _target.DynamicInvoke(_args);
}
public object Result
{
get { return _result; }
}
}
Now, to execute this command/operation asynchronously, we can use the Thread/ThreadPool class. Given below is a helper that wraps the ThreadPool class. All you need to do is call the static method Invoke passing it an instance the command object. Once again, this command object represents the job to be executed. Note that the Command object is passed as a state object (second parameter) to the QueueUserWorkItem method.
//Just a wrapper to the thread pool class
public class ThreadPoolHelper
{
private static WaitCallback dynamicInvokeShim = new WaitCallback(CommandInvoker);
private static void CommandInvoker(object o)
{
Command command = (Command) o;
command.InvokeCommand();
}
public static bool Invoke(Command command)
{
return ThreadPool.QueueUserWorkItem(dynamicInvokeShim, command);
}
}
Now let's see how the Command is used (the 'Receiver'). Shown below is a totally arbitrary class using the command:
public class MyClass
{
private delegate int AddDelegate(int a, int b);
public void TestCommandPattern()
{
Delegate dlg = new AddDelegate(Add);
//Command to invoke the add operation
Command command = new Command(dlg, new object[] {5, 5});
ThreadPoolHelper.Invoke(command);
//Command to invoke the do nothing operation
command = new Command(new ThreadStart(JustDoIt), null);
ThreadPoolHelper.Invoke(command);
}
//Sample method
private int Add(int a, int b)
{
return a + b;
}
//Sample method
private void JustDoIt()
{
Console.WriteLine("Nothing!");
}
}
Now, many of you would be ready to pounce on me with the suggestion that BeginInvoke/EndInvoke combination on the delegate offers a similar solution, perhaps more cleanly & efficiently. Well yes, I do agree. I gave the above example as a good illustration of the command pattern and moreover, this method is still apt if you employ the Thread class (Note the BeginInvoke involves a threadpool thread)
In my subsuquent posts, I shall try to cite more such application of patterns in .NET. If there are better examples, or if my citations are flawed in any way, please feel free to drop in your comments. Thanks!