VS2008 Code Refactoring – Extract, Encapsulate, Reorder and Rename!

This is a great tool and one you must know – mainly because it will save you time and do a lot of tedious coding for you.

Best way to learn is to open up an old project you did some years ago. Hopefully with all the stuff you have learned since then you will look at the code and go “jezuz h crickey – what a mess!” – I know I do.

So, in stead of rewriting all this manually (and wearing your ctrl+c and ctrl+v keys down to the table in the process) start using the VS200x code refactoring menu.

Maybe you have some hideous long methods that you have to scroll to see – select some suitable part of the code, right-click and choose Refactor -> Extract Method.
This is probably the most useful and rewarding of the refactor tools. It’s a very clever little thing, and it will automatically work out the necessary parameters and return type based on your logic.

Another great feature is the Refactor -> Rename tool – use this on any member that you want to rename – this will check through ALL your code (using the compiled binary) and ensure that you didn’t accidentally miss out some hidden reference somewhere. Also you get a preview of all the changes.

Yet another great feature is Extract Interface (so select some members that you want defined in a new underlying interface) – and indeed the Encapsulate Field which saves you writing the horrendously tedious get and set methods for your properties (thou you might want to have a look at the auto implemented get; set; properties in .NET 3.5).

Full details on the refactoring options available here: http://msdn.microsoft.com/en-us/library/719exd8s.aspx

The VS2008 refactoring menu is a great tool, and one you should make a part of your daily coding routine – and while you’re in the right-click menu have a look at the “surround with” and “snippets” menus as well, though tbh you can get too lazy and it might be easier to actually just write your if(…){} structures… or you could hire someone to do it for you if it’s becoming that painful.

Finally, if you like the refactor tools you might be interested in the (commercial) ReSharper tool, which extends the above as well as adding a plethora of tools and coding tips for your VS200x IDE: http://www.jetbrains.com/resharper/


Leave a Reply

Please log in using one of these methods to post your comment:

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: