If you haven’t seen Visual Studio Whidbey beta releases, you might not have heard of “refactoring”. Refactoring is cool, and once you see it, you’re going to use it a lot. Here’s a brief explanation.
In the past, source code editor tools have been kinda dumb. OK, you can enter your code and the editor will format it and keep it pretty. Some editors even allow you to collapse and expand methods and classes. Bookmarks and search/replace tools can speed things up. However, the editor has no real understanding of the source code. Sure, the good ones make sure you close a bracket and add a semicolon, but the editor is still on the dumb side.
This is where refactoring comes in. Refactoring gives the editor some smarts. The editor can look at the source code, and understand enough to make some intelligent changes that won’t mess everything up for you.
Here’s a good example – let’s say you want to rename a method from MethodBuildMoonbase() to MethodBuildBase(). One way to do that would be to globally search and replace the string “Moon” with “” to delete it. But if you do that, you’ll also delete Moon from variable names, string tables, and who knows what else. So you might decide to search for only MethodBuildMoonbase, but then you run into problems updating the method name AND everywhere it’s used. I’m not saying it’s impossible, just that it is fiddly, and if you make a mistake, you risk corrupting your source code.
“Wouldn’t it be better”, you might be wondering, “if there was some cool feature whereby the editor knew that I wanted to make changes to a token, such as a method name, and then make the changes only where it made sense?”. Of course it would – and that’s exactly what refactoring will do for you. Or at least, that’s one thing that refactoring will do.
For example, if you highlight a method name, and then select Rename from the Refactor menu, you’ll see a dialog that gives you some options. The default options are fine in most cases, so just enter the new name for your method and click on OK. You then see a preview pane displaying in day-glo yellow exactly what is going to happen – if you agree that it’s a Good Thing, click on Apply and it will happen.
The refactor menu has some other options too: for example, Extract Method. This one is great – you highlight a block of code, and the editor will create a brand new method containing that code, and put a call to the method where the code was. It’ll handle parameters in a sensible way too. The other refactor options are worth playing with as well.