ReSharper Series - Part 2: Basic Navigation

by Rasmus Kromann-Larsen January 27, 2009 22:42

At part 2 of the ReSharper series, we will attempt to enable more "no mouse survival". We will take a look at navigating between files without using the mouse. This is also a great chance to mention that not all the stuff you will see here is exclusive ReSharper stuff, some times I will throw in some Visual Studio shortcuts - the essence is to increase productivity - not religiously using one product for everything. In addition I have been using the combination for so long that I am often confused what is what.

Opening Files

ReSharper offers many ways of navigating between files based on what you need - and we are going to look at a few basic ones today.

The first one is called Go to Type and is activated through Ctrl+T [IntelliJ: Ctrl+N]. This will bring up the window shown below. Basically it's a quick search in all your classes.

image

Most often, navigating types is what you want, but sometimes it can be useful to navigate files instead, especially for configuration files, NHibernate mappings and other special files. ReSharper has a Go to File shortcut that brings up the following window - Ctrl+Shift+T [IntelliJ: Ctrl+Shift+N]:

image

Both of the search windows allow * wildcards, like in the below search where I wanted to find all the files that contain the word "Base":

image

They also allow the use of the + wildcard to denote one or more characters...

image

... and the ? wildcard to denote zero or one character:

image

Closing Files

Closing tabs in the visual studio editor is as easy as pressing Ctrl+F4. Not a ReSharper shortcut - but nice to know.

Accessing the Solution Explorer

While ReSharper gives us a nice way of opening files by name, it can still be useful to bring out the good ol' Solution Explorer once in a while. There's two shortcuts for this. There is a standard Visual Studio shortcut which will bring up the Solution Explorer tool - Alt+Ctrl+L. This will open the tool in it's current configuration - like you left it.

Lets imagine that I am browsing the MVC source - standing in the ControllerBase file in the System.Web.Mvc project. In my Solution Explorer I browse to the MvcFutures project to see something. After leaving the Solution Explorer, pressing Alt+Ctrl+L will bring me to my last location again:

image

However ReSharper also has a shortcut for bringing up the Solution Explorer - it is called Locate in Solution Explorer - Alt+Shift+L. Using this in the previous situation will actually track the current file and open the Solution Explorer with this file highlighted, as shown below:

image

I actually find both shortcuts useful in different situations - but play around with it and see what works for you.

Escaping Tools

Another quick Visual Studio tip - the Solution Explorer and other tools you might activate while coding are easy to deactivate again with a quick Esc. This will bring the focus back to the code editor.

kick it on DotNetKicks.com

Tags:

ReSharper

Testing a Visitor - Mocking and Test Readability

by Rasmus Kromann-Larsen January 22, 2009 21:53

The other day I was using TDD to write a visitor for an object graph at work. I often use mocks a lot and was using mocks in this particular batch of tests as well. However, in the end creating my own fake class turned out to be much better (in my opinion). Favoring state-based testing over interaction-based testing (sometimes) can really simplify the noise within a test and provide clarity.

What I wanted to test was that objects of the correct types were visited from the parent object and was thus producing a number of tests that look something like this:

private MockRepository mocks;

[SetUp]
public void Setup()
{
    mocks = new MockRepository();
}

[Test]
public void ShouldVisitObject1BelowRootObject()
{
    var rootObject = ObjectMother.Build<RootObject>();

    var object1 = ObjectMother.Build<Object1>();
    rootObject.AddObject(object1);

    var visitor = mocks.DynamicMock<IVisitor>();

    using (mocks.Record())
    {
        Expect.Call(delegate { visitor.Visit(object1); });
    }

    using (mocks.Playback())
    {
        rootObject.Accept(visitor);
    }
}

Now this was a pretty big object graph, so there were a lot of tests that looked very much like this one. What I am doing here is interaction-based testing, using a mock to verify that my class under test calls a particular method. There is quite a bit of mock noise in this test, stuff that is related to setting up mocks and our expectations. Noise like this can be much worse - and it was worse in my production code.

In this particular model, all the objects have a collection of sub items - and this collection conveniently contained some the various object types to visit. So I had a lot of tests that very almost identical to the one above. I thought I'd be clever and refactor my tests so I wouldn't have to duplicate as much code for each of these particular cases. After wrestling with it for a bit I came up with this:

private MockRepository mocks;

[SetUp]
public void Setup()
{
    mocks = new MockRepository();
}

[Test]
public void ShouldVisitObject1BelowRootObject()
{
    TestVisitor<RootObject, Object1>(
        delegate(IVisitor visitor, Object1 obj)
        {
            visitor.Visit(obj);
        });
}

It still looks kind of weird, with the delegate floating around (using C# 2.0 at work for now, so no lambda syntax). The test is still arguably even less readable. The delegate is actually used in the helper method to add the expectation to the mock, since the visitor has overload methods for concrete classes (this is the whole idea of visitor, implementing double dispatch - promise I will post about it soon), you can't really abuse generics.

The helper method is shown below and is also kind of hairy.

private delegate void VisitExpectDelegate<T>(IVisitor visitor, T child);

private void TestVisitor<TParent, TChild>(VisitExpectDelegate<TChild> visitExpectDelegate)
    where TParent : AbstractObject
    where TChild : AbstractObject
{
    var parent = ObjectMother.Build<TParent>();
    var child = ObjectMother.Build<TChild>();
    parent.AddObject(child);

    var visitor = mocks.DynamicMock<IVisitor>();

    using (mocks.Record())
    {
        visitExpectDelegate(visitor, child);
    }

    using (mocks.Playback())
    {
        parent.Accept(visitor);
    }
}

Another small thing that annoyed me besides the readability issue is that the code only works for a very specific case, checking that sub items are visited below a parent object. Furthermore, trying to mock visitor behavior of a deeper class hierarchy can turn into a mocking headache real fast.

I asked a colleague about the readability of my test and if he thought it was acceptable. He suggested that I tried faking (creating my own class) the visitor instead of mocking it. In essence, he suggested that I'd use state-based testing over my current interaction-based method.

The result was this:

private CountingVisitor visited;

[SetUp]
public void Setup()
{
    visited = new CountingVisitor();
}

[Test]
public void ShouldVisitObject1BelowRootObject()
{
    var rootObject = ObjectMother.Build<RootObject>();
    rootObject.AddObject(ObjectMother.Build<Object1>());

    rootObject.Accept(visited);

    Assert.That(visited.TotalCount, Is.EqualTo(2));
    Assert.That(visited.GetCount<Object1>(), Is.EqualTo(1));
}

My fake was basically just a visitor that would count how many times it had visited a given type of object and the total count of visits it had made. For me this test is so much more readable - build an object graph, give it to the visitor, make asserts about the visit count using NUnit's "Assert.That" syntax. The cool thing about this is that it makes no assumptions about sub items and can actually be used for any visitor that visits any object graph. It could also test deeper object graphs with ease. I am aware that it doesn't test which particular instances are visited, but I didn't feel that it would add much value to add this to the visitor, although it is possible.

The fake visitor looks like this and is really just a few generic tricks and a dictionary.

private class CountingVisitor : IVisitor
{
    private readonly Dictionary<Type, int> _count = new Dictionary<Type, int>();
    private int _totalCount = 0;

    private void Add<T>(T obj)
    {
        if (!_count.ContainsKey(typeof(T))) _count[typeof(T)] = 0;
        _count[typeof (T)] += 1;
        _totalCount += 1;
    }

    public int TotalCount
    {
        get { return _totalCount; }
    }

    public int GetCount<T>()
    {
        if(!_count.ContainsKey(typeof(T))) return 0;
        return _count[typeof (T)];
    }

    public void Visit(RootObject obj) { Add(obj); }
    public void Visit(Object1 obj) { Add(obj); }
    public void Visit(Object2 obj) { Add(obj); }
}

So remember the state-based testing, mocks are useful animals and sometimes they will be the only reasonable way or the easiest and you should use them, but other types of fakes (particularly hand-crafted ones - I think this one is actually called a "spy") can really give a good boost in readability and flexibility with a minimal code effort.

kick it on DotNetKicks.com

Tags: , , , ,

Development | Testing

ReSharper Series - Part 1: The Power of Alt+Enter

by Rasmus Kromann-Larsen January 21, 2009 20:32

Woo, finally hit part 1 of the ReSharper series and ready to start on the basics of ReSharper. Today we will look at the basic look and feel after you have installed ReSharper and fired up your Visual Studio. Learn one of the most basic commands.

The single thing you will probably use most in ReSharper is the quick-fix command - which is initiated using Alt+Enter. This is a context-based command which will suggest actions based on where your cursor is located. ReSharper provides different visual cues to alert you that an action is available. Lets look at a few examples of the versatility of this command.

Implementing Missing Methods

Say I am implementing the standard Account class and want to check something with the balance when doing a withdrawal. As I write the code shown below, ReSharper will pop up a red light-bulb on the left of my method as my cursor is on it. This is ReSharper's way of telling me that an action is available.

image

When you see a yellow or red light-bulb, pressing Alt+Enter brings up the action menu:

image

In this case, ReSharper is offering to create the missing method for me. Picking the default option by hitting the Enter key creates the new method with a default implementation:

image

ReSharper will show these light yellow boxes for on our new method for things that we might want to change. They don't go too well with my color scheme, but the idea is that ReSharper suggests a return value, a method name and types/names of the arguments. It is easy to navigate between the yellow boxes using either Enter or Tab.

After all the yellow boxes have been resolved (just pressing Enter to go with the default) the whole exception line will be selected and we're ready to start implementing our method.

Errors like this will also often show up as red squigglies like the ones you know from Word.

Removing Dead Code

Another thing you will probably notice after installing ReSharper is that some of your text turns gray like this:

image

Gray text is ReSharper's way of letting us know we have dead or unused code. We are not using the amount argument for anything in the method and thus it can safely be removed. Placing our cursor on amount, another light-bulb pops up and gives us the following context menu:

image

This is where we start benefiting from the fact that ReSharper knows the structure of our code. It is suggesting that we remove the parameter and update the usages. In this simple example, the only usage is the Withdraw method above, but this will actually work on much more advanced examples. Accepting the action with Enter removes the parameter and also changes the code in Withdraw method:

image

ReSharper also checks your import statements to see if you are importing namespaces that you are not using and suggests removing them like so:

image

Later in the series, we will look at some of ReSharper's options for choosing namespaces to always import some often used namespaces and ignoring them when scanning for use.

Importing Namespaces

When using types in namespaces that you have not imported, ReSharper will pop up a blue square to suggest an import like so:

image

No more writing using statements by hand. Recently I've started using ReSharper's auto-completion (will be visited one of the next parts) for this, but it's still a very useful feature, again using Alt+Enter.

Hints and Suggestions

ReSharper also supports hints and suggestions, both are actually suggestions for changing something in your code, but hints are less obtrusive and won't show up when navigating between suggestions and not show up on the scrollbar in the code editor.

image

If we look at this bit of code, we notice that the List<string> has a solid green underline - this is a hint. The new keyword has a green squiggly line, which denotes a suggestion. Looking at the scrollbar to the right in our code editor, there's a small green line - this is ReSharper telling us that there is a suggestion at this point in our code. Hovering the mouse over the line tells us what the suggestion is. Warnings and Errors will show up as yellow and red lines. The hint is not shown as mentioned.

image

Let us deal with the hint first. This hint is actually for us to use the C# 3.0 var keyword instead of our List<string>.

image

I usually don't like this hint so much, since I feel it sometimes reduces the readability of my code if I overuse the var keyword - luckily there is an option in the context menu to change the inspection options for the particular hint. Pressing Enter brings up the following dialog:

image

Here I can set the severity of not using the var keyword when possible. Since I don't like it - I choose "Do not show" and press OK. Now the solid green line is gone. Proceeding to press Alt+Enter on the suggestion asks me if I want to use a collection initializer instead of calling the add method on the next line:

image

Accepting this removed the call to Add and uses the collection initializer - as expected.

image

Context Is King

This post shows some examples of how ReSharper uses the context of your code to suggest "intelligent" options. All examples in this post were resolved pressing Alt+Enter. Using this single key combination can save you a lot of writing and often even suggest things that you didn't think of. But remember to consider what it's suggestion (like the var keyword) instead of just doing everything blindly.

kick it on DotNetKicks.com

Tags:

ReSharper

ReSharper Series - Part 0: Installation

by Rasmus Kromann-Larsen January 17, 2009 11:05

imageWelcome to the 0. part of my ReSharper series - almost at the "real" ReSharper content now, but we just need to get the Resharper installation out of the way. It's not really that hard either.

ReSharper Installation

This series is based on ReSharper 4.1 - as this is the newest version. You can download it directly from here. Once you get past the installation, just fire up Visual Studio and it should present you with options to use either Visual Studio or IntelliJ bindings. I've gone with the IntelliJ bindings for my setup, so this is what this series is going to be based on. I am using the Visual Studio bindings, and will provide information for both keyboard layouts in this series.

If you already installed ReSharper earlier and want to switch to either of the bindings, you can do so in the ReSharper Options in the General section:

image

The first time you use some of the shortcut keys that clash with Visual Studios bindings, you will get a dialog like the one below:

image

I usually just check "Apply to all ReSharper shortcuts". Haven't had a problem with it yet. Then you should be set for starting up with ReSharper.

Additional Suggestions

Other than installing ReSharper, I've found it helpful to print the cheatsheet from the JetBrains ReSharper documentation page. It can be found here.

I also recommend picking up Roy Osherove's Keyboard Jedi - pressing Ctrl+Alt+Shift+F12 will disable the mouse in the application that currently has focus. I've found this to be a very healthy technique when figuring out how much you really use your mouse - and force you to look for those keyboard shortcuts. It sounds silly, but it can really change the way to work when the mouse is just not available. Just enable it one hour each day.

kick it on DotNetKicks.com

Tags:

ReSharper

ReSharper Series - Part -1: My Visual Studio Setup

by Rasmus Kromann-Larsen January 13, 2009 19:08

So it's time for part -1 in my blog series about ReSharper. We're still in the negative parts, since we're not dealing with ReSharper yet, so much introduction to do. Today is going to be about my personal Visual Studio setup - and the source code setup for this series. I'll do a lot of screenshotting in the series, so you might as well see how my setup is.

ASP.NET MVC Beta Source

I needed some source code for my examples. When we get to the navigation parts of the series, I'll need some actual code to explore and I wanted to use some publicly available code, so it would be possible for people to follow along in some of the examples if they wanted to. So I picked the ASP.NET MVC Beta Source code as my base for playing with Resharper. It can be downloaded here.

Physical Setup

I run with a dual monitor setup at home with two Samsung monitors and find that is a real productivity booster. Highly recommended. My main monitor is a 22" wide-screen Samsung 2253BW and my secondary monitor is a 19" Samsung SyncMaster 971p. I love the 22" wide-screen for it's size - and the 971p has a truly amazing contrast which is really nice for doing graphical work of any kind. I would post a photo, but my desk is too messy at the moment. Oh, and on the subject of multiple monitors, I highly recommend using MultiMon or UltraMon for providing monitor-specific taskbars and hotkeys for moving windows between monitors.

Visual Studio Layout

I prefer to work with a dark background when I'm coding, since monitors use additive colors, having a white background simply emits way too much light and my eyes get tired more quickly. I happened to find a theme Rob Conery modified to look like the vibrant ink theme from TextMate. Robs version can be found here. It looks like this (although I'm using Courier New instead of Consolas - old habit):

image

You will also notice that all my windows are set to auto-hide. This discourages me from clicking on stuff with my mouse and I can easily bring up most of what I need with keyboard shortcuts anyway.

AnkhSvn

While this is not really ReSharper related at all, I feel that I must mention the incredible (and free) AnkhSvn add-in for managing subversion. I tried the first versions and it really sucked, but now that version 2 is out, it's really the best out there in my opinion.

kick it on DotNetKicks.com

Tags:

ReSharper

Reducing Check-In Friction (in Continuous Integration)

by Rasmus Kromann-Larsen January 11, 2009 21:43

In a continuous integration environment, one of main motivations is to avoid big bang integrations, where multiple people and/or multiple teams build their part of the project and it is all fused together before release. The benefits of having an automated continuous build are huge, since problems become visible early. The build server polls the source control server and produces a build and runs the appropriate tests when new code is checked in.

imageTo have an efficient continuous integration environment, changes should be checked in often. Not checking in often results in more merge conflicts, less visibility of current project status) and reduced benefits from source control in general (less check-ins mean less chance of rolling back, bigger risk of loosing code). To encourage developers to check in their code often, it should be a non-event - it should be easy and not dangerous. However, continuous integration is all about visualizing build failure, where you use a simple tray application, lava lamps or whatnot. So checking in something that doesn't work can cause some developer stress, rushing to fix the build.

When the build is broken, other developers can't check in or out (at least they shouldn't - they will either make the problems worse or get broken code), so you want to minimize the time the build is broken. It is useful to have some discipline about the process of checking in, like the "Check In Dance" described Jeremy Miller's post. In general you want to make sure of the following:

  • You have the latest bits from source control.
  • The code can build successfully.
  • Relevant tests pass (unit tests, maybe static analysis tools like FxCop)

Jeremy also describes notifying the team that a change is coming. While this might be a good idea for smaller teams, I find that it would be rather disturbing if you are part of a bigger team (10-20+ developers). In this case I would opt for a more optimistic check-in policy, assuming that check-ins won't happen at the same time or won't clash. It involves slightly more praying and can give some annoying conflicts sometimes though.

Reducing friction on the check-in process is important. To make check-in a non-event, it needs to be very simple for the developer. A good solution for this is often to have a "smoke-screen" to verify the quality of your code before checking in. If you look at the above steps, it is rather simple to collect them in a single build target that could be run easily by the developer. This will also increase developer confidence in not breaking the build, thus eliminating check-in fear and enabling often check-in.

You will want to make sure that the build target can be executed in a few minutes and that tools like FxCop use identical settings on developer machines and build server (personal experience). Another option is to use pre-tested check-ins if you are using TeamCity, but I find that the build target will serve the purpose just as well.

I hope you enjoyed the post. May your future builds be green.

kick it on DotNetKicks.com

Tags: ,

Development

ReSharper Series - Part -2: Introduction & Motivation

by Rasmus Kromann-Larsen January 10, 2009 12:44
image

This is the first and -2. part of my ReSharper series. -2 because it there's still a few parts until I hit real ReSharper content. The subject today will be a quick introduction to ReSharper and the motivation for using it - so why should we?

What is ReSharper?

ReSharper is a Visual Studio add-in made by JetBrains. In their words, ReSharper is:

The most intelligent add-in to Visual Studio.

What it really amounts to is a lot of smart static analysis of your code, much like Visual Studio does already to provide you with IntelliSense and red squigglies when you make mistakes. What they do with this information is to provide context-based suggestions and generally reduce the number of keystrokes required to produce the most common code scenarios.

In addition to this, the static analysis information can be used to provide a structured way to refactor your code without resorting to error-prone search and replace techniques. Since ReSharper "knows" the structure of your code, it can provide much better support for stuff like renaming classes, extracting and moving functionality.

Strengths

From my point of view and experience the main strength of ReSharper is it's context-awareness. This is what gives the intelligent and intuitive feel when using it. Since ReSharper provides a lot of functionality, filtering it by what is available (or reasonable) at this given point in the code is really valuable.

Besides context-awareness, I really love the navigation options provided by ReSharper. It allows me to navigate along different axis depending on what I'm looking for. Providing easy options for navigating according to usages (where is this method called from), inheritance trees (superclasses/interfaces/subclasses) or completely different files, depending on which aspects of the code I am exploring at the given moment.

Third is code-generation and refactoring. This is often mentioned as the main strength of ReSharper - this is mostly convenience, reducing the amount of manual work required to do refactoring and doing (mostly small-scale) code generation used to create the usual cruft code for classes, properties and such.

Weaknesses

Seems odd to talk about weaknesses in this motivation post, but this isn't really weaknesses in ReSharper per se, but more things I still feel I'm missing. I actually feel that ReSharper is doing the job it is supposed to do quite well.

At the moment, ReSharper is the only real productivity add-in I use in Visual Studio - but I feel I'm missing features for basic text editor stuff, quick navigation in the current file (ReSharper provides some, but it can be heavy sometimes). It seems that the vim add-in ViEmu might be some of what I'm looking for. Maybe after I'm done with this series.

kick it on DotNetKicks.com

Tags: ,

ReSharper

ReSharper Series

by Rasmus Kromann-Larsen January 10, 2009 12:43

As I've mentioned earlier on twitter, I've been planning on doing a ReSharper series on my blog. The idea is to go over ReSharper one part at a time and find some new quirk or feature that I'd like to highlight. I have used ReSharper for a very long time, but want to dig even deeper and try to pass some of the knowledge as well. I have already learned a great deal more just researching for this series.

We're going to start from the basics and go from installation over the basic features of ReSharper to some more advanced and exotic features. The whole event is going to have a strong focus on utilizing the keyboard as much as possible - surviving without your mouse. The reason for this is simply that I've found that in most cases, this will boost the productivity - once you really know keyboard shortcuts, I feel the keyboard just almost becomes a natural extension of your mind, allowing for very rapid work.

I will be updating this post to serve as a reference and overview for the parts as I'm progressing. The number of posts is not decided yet, but suggestions and feedback is very welcome and will probably make me do more posts.

Disclaimer: This blog is not affiliated with JetBrains.

List of posts (will be updated):

kick it on DotNetKicks.com

Tags:

ReSharper

Craftsmanship over Crap

by Rasmus Kromann-Larsen January 06, 2009 19:55

I was catching up on my blog reading (ObjectMentor to be more specific) when I found Uncle Bob's post on quintessence as the fifth element for the Agile Manifesto. His statement of "Craftsmanship over Crap" really rang true with me.

We (software developers) like to compare our work to that of craftsmen and many people are starting to realize that maintainability is one of the cornerstones of writing good software. However, our software still keeps decaying, brilliant designs are mangled with hacks, quick bug fixes or just plain outdated with changing requirements.

However, I challenge you, next time you go to fix that bug or that small change request that almost fits the current design, step back and think first. Spend those extra minutes considering if there is a way you can fix it, maybe even improving the current design. Don't go on an overengineering spree, just keep it simple and elegant. Then, when you're done, sit back and marvel at your work and smile.

We've all made a quick hack, we will all do it again, but I promise you, those few extra minutes spent will be worth it in the long run. Technical debt has high interests. How often have you made a quick change while thinking (or even better made a comment) that you will come back and fix it later. How often have you forgotten?

Actively thinking about this and being proud of the results is really good for my personal productivity. Ideally, if you always leave your code slightly better than you found it, it should resist decay very well. Challenge your team to join you in this quest.

 

- Leave the code slightly better than you found it.

- Write a regression test for a bug, so it's not reintroduced.

- Don't live in a house with broken windows.

- Write tests to gain the confidence to perform refactoring.

- Be a craftsman.

 

And to quote J.P Boodhoo: 'Develop with Passion'.

kick it on DotNetKicks.com

Tags: , , ,

Craftsmanship | Development

Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant | Adjusted by Rasmus Kromann-Larsen

About Me

I am a danish .NET developer blogging about the technical side of my life, mostly .NET stuff, but also fundamental topics like design patterns, principles and productivity boosters.

In addition, I am a core group member of Aarhus .NET User Group.