A View Inside My Head

Jason's Random Thoughts of Interest


CodeRush: Anonymous Method Refactoring Fun

I recently had to work with some code that I wrote a few years ago, and stumbled upon this:

Code showing an anonymous method being used as an Action delegate in Array.ForEach
(Not that it's relevant to the rest of this blog post, but this code was responsible for deleting a Role in a custom membership provider, but due to foreign key relationships without cascading deletes, all of the User/Role assignments had to be deleted first)

Now, in all fairness to myself, there's really nothing wrong with this code.  Array.ForEach<T> requires an Action<T> delegate, and this anonymous method certainly qualifies as one.

However, since the time that I wrote this particular piece of code, I started using Lambda expressions more often.  To be consistent with the rest of the project's code, I should change this anonymous method into a Lambda expression.

Fortunately, CodeRush makes this a breeze!  Simply put your cursor within with anonymous method itself, and then hit your Refactor Key and choose the "Compress to Lambda Expression" refactoring:

Compress to Lambda Expression refactoring
As simple as that, the wordy "delegate" syntax of the anonymous method is compressed into the terse "=>" syntax of a Lambda expression:

Array.ForEach with a Lambda Expression as the Action<T> delegate
But, suppose that you are just learning Lambda expressions, and come across one in code that you don't fully understand.  CodeRush allows you to go the other way, too, and expand a Lambda expression into an anonymous method, which may be easier to understand.  Similar to above, put your cursor on the Lambda expression, hit the Refactor Key, and then choose "Expand Lambda Expression":

Expand Lambda Expression refactoring
Anonymous methods were introduced as a way to inline functionality that otherwise had to exist in its own named method.  This is really only good if that functionality is used one time.  But, what if you discover that the functionality is needed in multiple places?

CodeRush provides a refactoring for anonymous methods called "Name Anonymous Method" that will extract the logic into a named method that can then be called from other code:

Name Anonymous Method refactoring
Activating this refactoring will first display the Target Picker (red arrow and line) so that you can select where to add the new method.  Then, the new method's name can be set by editing the text in the green box that will appear.

Finally, suppose that the opposite is true: you have a named method that is only used in one place, and would prefer to just inline that code.  Or, perhaps you would like to create a one-off modification to an existing method, and don't need the new functionality to be in its own named method.

CodeRush has a refactoring called "Inline Delegate" that replaces a delegate referring to a named method with an anonymous method.  If there is only a single reference to that named method, then this refactoring will also delete the named method altogether.

Inline Delegate refactoring

Since I was already familiar with the anonymous method syntax, CodeRush played an instrumental part in my learning Lambda expressions because I could write an anonymous method and then have it transformed into an equivalent Lambda for me.  But, once I knew Lambdas, I found that I wanted to update my older code in order to replace anonymous methods with the newer syntax, and CodeRush made it a trivial task to do this.

Happy Coding!

CodeRush: CodeRush Tool Window

CodeRush is full of templates.  Thousands of them, when you combine the basic templates with the various types that are supported by each.  How does someone start to learn all of the required mnemonics in order to use CodeRush effectively?

The answer to that is a brilliant feature known as the CodeRush Tool Window:

DevExpress, Tool Windows, CodeRush

(DevExpress menu in Visual Studio, Tool Windows -> CodeRush)

The CodeRush Tool Window provides a context-sensitive list of "next characters" in CodeRush templates that are valid at the cursor's current location.  As you start to work with CodeRush, leave this window open (perhaps on a second monitor) so that you can train yourself.

CodeRush Tool Window docked on the left

In the screenshot above, I have the CodeRush Tool Window docked on the left side of my IDE.  Depending on where my cursor is located, the contents of the window will change.

For example, I can create a new Auto-Implemented Property at the cursor's current location (line 49 in the screenshot).  In the CodeRush Tool Window, I see that mnemonics for Auto-Implemented Properties start with "a", so I can type that character.  But, after typing "a", the contents of the CodeRush window will change:

CodeRush Tool Window after starting a mnemonic

The letter "a" by itself is a valid mnemonic for a CodeRush Template, as indicated by the the green "expansion" frame at the top of the CodeRush Tool Window.  If I were to hit the spacebar here, I'd get code for a new abstract class (a preview of this code appears in the expansion frame).  This is not what I want, so I can look in the list to see if typing more characters results in an appropriate mnemonic.  Note: If you do accidentally expand a wrong template, just perform an Undo (Ctrl-Z) to return to the pre-expansion state of your code.

Suppose that I was trying to create an Auto-Implemented Property of type Boolean.  From the contents of the window, I see that "ab" is listed as "bool", and so I only need to type the second character ("b") and then hit the space bar.

Play around by moving your cursor to various places in your code, and observing how the contents of the CodeRush Tool Window changes.  Try out some of the template mnemonics that are listed to see how they work.  Remember that Undo (Ctrl-Z) will get you back to where you started.

Happy Coding!

CodeRush: Property Templates

There is A LOT of repetition in coding.  To accomplish certain things, you often need to include boilerplate code that is repeated throughout your program. 

Take Properties, for instance.  Defining Properties on a class, especially a lot of them, can be a very tedious task. 

Traditionally, you have to create a member variable of the class to serve as the Property's backing store, and then create the Property itself (with a getter and setter to interact with that member variable).  Lather, rinse, repeat... ad nauseum.

Traditional Property syntax written in C#

This type of work is where CodeRush excels by providing you with mnemonic-driven code templates.  In other words, you type a few characters (the mnemonic), hit the space bar, and it will expand into a much larger snippet of code for you (saving you scores of keystrokes in the process).

The most basic template to help with writing Properties is: p

Move your cursor to somewhere within your class { } block, where defining a Property is legal syntax, and then type 'p' followed by a space.  This will expand into the following:

CodeRush p template expanded
The cursor will be placed in the first orange box, where you can change the data type from "object" to whatever type your Property needs (i.e., "string").  Notice that the Property's type is linked to the backing store's type, so changing one of them will change the other.

The trick with the orange boxes in CodeRush is that you press Enter when you finish editing their contents.  This will remove the orange coloring from that element, and move the focus to the next orange box within the template.  Keep repeating this until there are no more orange boxes left to edit.

Since we knew this was a string Property, we could have saved even more keystrokes by using a mnemonic that included the type: ps

CodeRush ps template expanded

The only real difference between "p" and "ps" is that the type will already be set to "string" for you in the latter.  There are other mnemonic templates that expand into Property definitions for other types, like "pi" for "int" and "pd8" for "DateTime".  (I'll blog about an awesome discovery feature to help you learn these in my next blog post).

But, wait!  There's more!

If you already have a member variable defined (maybe you used the "vs" mnemonic, which expands into a private string variable), and wish to create a Property in your class that uses this variable as a backing store...  well, CodeRush has a trick to help you accomplish that!

private string _MyCoolString;
Simply copy that line of source code into the copy buffer as you normally would (i.e., select the line, and then hit Ctrl-C).  Now, paste it where you would like the Property to be created (i.e., maybe on the line directly below).  Since it's illegal to define this variable twice, CodeRush does something awesome called a Intelligent Paste.  In this case, based on the contents of the copy buffer, it expands a Property template that uses your variable as the backing store!

SmartPaste with property expanded

Similarly, you can also use the "Encapsulate Field" refactoring instead of the Intelligent Paste.  Move your cursor to the line declaring the variable to use as a backing store, and then hit your Refactor Key.  Use the Down Arrow key to move through the list of available refactorings, and press Enter when "Encapsulate Field" is highlighted.

Encapculate Field refactoring
Next, CodeRush will prompt you where you would like to insert the code.  Use the Up and Down arrows to move through valid places where the new code can be inserted.  Press Enter to select the location designated by the Target Picker (red arrow).

Insertion Point
The result will be a new property with a getter and setter that uses your variable as a backing store.

New property inserted

And, finally, as C# evolved, Microsoft recognized that a lot of Properties that were being created were very simple in nature, requiring no logic in the getters and setters other than reading and writing to their backing store.  A new Property syntax was added that did not require a backing store to be explicitly defined (or rather, the compiler actually creates one for you behind the scenes).  This new syntax is referred to as an Auto-Implemented Property.

Similar to the "ps" template, you can use "as" to create an Auto-Implemented Property of type "string". 

CodeRush "as" template expanded
Note: "a" by itself will not expand into an Auto-Implemented Property of type "object" similar to what "p" by itself does.

What? You didn't know about Auto-Implemented Properties, or you want to convert all of your old-style Properties to the new Auto-Implemented Properties?  There happens to be a refactoring for that in CodeRush!

Move your cursor to the Property definition that you would like to convert, and then hit your Refactor Key.  Use the Down Arrow to select "Convert to Auto-implemented Property", and observe the changes that CodeRush will be making to your code (the changes will be painted on top of the code that will be changed).  Press the Enter key, and voila!  No more backing store!

Convert to Auto-implemented Property

(credit goes to Dennis Burton for telling me about this refactoring... which goes to prove that there are way more features in this tool than you'll likely ever master)

Thanks to the magic of CodeRush, you now have many different ways to quickly create properties in your code, saving hundreds (if not thousands) of keystrokes in the process. 

Happy Coding!

CodeRush: The Refactor Key

Do a search, and you will find that there are a few IDE Productivity Tools available for Visual Studio. As far as feature sets go, you'll also find that there is quite a bit of overlap in what these tools offer.  So, deciding on one is largely a matter of personal preference. 

However, by not using an IDE Productivity Tool at all, you are doing yourself a great disservice.  No, really!  You are wasting a lot of time by manually doing things instead of allowing software do it for you.  Since time is money, and these tools are not very expensive, you will quickly make up for the cost of the program in time savings alone (I think within the first week, if not the first day).

The one tool that I stand behind is CodeRush by DevExpress. Some of the finest people in the industry work for Devexpress, and over the years, some of these folks have become quite good friends of mine.  The company has an outstanding commitment to supporting the developer community year after year, and you will surely find them sponsoring a developer event near you.  Aside from the goodwill, their product suite is outstanding, so I'm proud to continue to use and recommend their entire product line whenever I can.

Sidebar: Personally, I think that DX has a bit of a branding problem with their IDE Productivity Tools, because CodeRush includes another product called Refactor! Pro.  I would rather see them not offer Rafactor! Pro by itself, and only sell CodeRush with Refactor! Pro, since in my mind they are together one product (and I would never recommend Refactor! to someone without CodeRush).  As such, I often refer to features from Refactor! as belonging to CodeRush.  But, I digress.

Learning any new tool can be a bit daunting at first, and CodeRush is certainly no exception.  DevExpress has produced a collection of short tutorial videos to help new users come up to speed.  It should be noted, though, that some of these videos are likely useful to experienced users as well: with so much functionality packed into the product, I find that it's common for someone to master a number of features, be familiar with just as many if not more features, and yet be totally unaware of half of the things that the tool has to offer.

Since you have to start somewhere, the first feature that I recommend that someone master is mapping and using their Refactor key.  This is a shortcut key that will open a CodeRush "context menu" to show available refactorings for the code where the cursor is currently located. 

Personally, this is the feature that I probably use the most, so finding an appropriate key binding that is easy to hit yet does not interfere with my ability to type code or use Visual Studio key bindings was important.  The default is Ctrl-backtick ( ` ), but I landed on the just backtick key to save me from needing to hold Ctrl.  I've heard of a few people who have picked F1 as a way of defeating the annoying help system in VS2008 and earlier.  It's all a matter of personal preference, so choose something that works for you.

To set the Refactor key shortcut, open the Options from the DevExpress menu in Visual Studio.  In the tree on the left, open IDE and click on Shortcuts.  After admiring the entire collection of shortcuts that are available, locate the "Refactor!" section in the list.  One of the defined shortcuts will be mapped to the "Refactor" command, and by clicking on this, you can set your own key to bind it to on the right.

Refactor key binding is set in the Visual Studio Devexpress Menu, Options, IDE - Shortcuts - Refactor! group

Trivia: Notice the Alternate Bindings that also appear in the same section. Number Pad 0 is the one preferred by Mark Miller.  Dustin Campbell has two bindings mapped: the default Ctrl-`, as well as Number Pad INS.

Now that you have a Refactor key, try moving your cursor to different places in your code and pressing it. 

Refactor key pressed on a variable

You'll still have to learn about different refactorings that are available in the tool, but hopefully the Refactor key will become your preferred portal for accessing those refactorings (instead of using smart tags or the mouse to right-click on code).

Happy Coding!