Showing posts with label imho. Show all posts
Showing posts with label imho. Show all posts

Saturday, 21 June 2008

Yet another way of raising events from mocks

Update 2008-06-26: This is now in the Rhino Mocks trunk, so it should be available as part of the 3.5 release.

I've been playing around with raising events from mocks for the last couple of nights, and think I've finally come up with an approach that works for me. Finding a nice way of raising these events is particularly tricky for mock object frameworks, as the C# compiler is really picky about how you can use event references. For example, let's look at a very useful interface:

public interface IDoSomething {    
    event EventHandler SomethingDone;
}

Outside of a class that implements IDoSomething, the only time we can reference SomethingDone is when we are adding or removing listeners (x.SomethingDone += someEventHandler; or x.SomethingDone -= someEventHandler;). (C#'s lack of real support for System.Void is partly to blame here, as both these operations are void.)

To raise an event on a mock object, it would be lovely to be able to code something like this:

var mock = mocks.DynamicMock();
mock.Raise(mock.SomethingDone, mock, EventArgs.Empty);

Unfortunately due to the aforementioned constraint, the emphasised part of the code will give a compiler error stating "The event 'IDoSomething.SomethingDone' can only appear on the left hand side of += or -=".

There are a few workarounds for this. Let's start with the standard Rhino Mocks approach. (I'm using Rhino Mocks 3.5 beta and xUnit.net here -- feel free to translate from [Fact] to [Test] if you use NUnit, MBUnit et al.)

[Fact]
public void Raise_event_old_style() {
    var mock = mocks.DynamicMock<IDoSomething>();
    mock.SomethingDone += null;
    IEventRaiser eventRaiser = LastCall.IgnoreArguments().GetEventRaiser();
    mocks.ReplayAll();

    var wasCalled = false;
    mock.SomethingDone += (sender, e) => wasCalled = true;
    eventRaiser.Raise(mock, EventArgs.Empty);

    mocks.VerifyAll();  
    Assert.True(wasCalled);
}

Rhino Mocks records the expectation that an event handler is added, then uses LastCall to ignore the argument and gets an IEventRaiser for the last event referenced. That IEventRaiser can be used later on to raise our event. Phil Haack has a helpful post which explains a bit more about this approach.

When I first saw this I must admit it seemed like a lot of noise that obscured what I was really trying to do. This got worse when I started playing around with the new Arrange - Act - Assert syntax and I didn't want to go through the whole replay / verify cycle. So I started looking at the Rhino Mocks implementation of IEventRaiser, the EventRaiser class. This class lets us do this:

[Fact]
public void Raise_event_using_string_for_event_name() {
    var mock = mocks.DynamicMock<IDoSomething>();
    var wasCalled = false;
    mock.SomethingDone += (sender, e) => wasCalled = true;

    var eventRaiser = EventRaiser.Create(mock, "SomethingDone");
    eventRaiser.Raise(mock, EventArgs.Empty);
    
    Assert.True(wasCalled);
}

Here we can specify the relevant event using a string. This works nicely and is easy to read, but causes problems when refactoring and means we don't get intellisense or compiler assistance. Ayende has written about this approach, comparing it with the LastCall.GetEventRaiser() approach we used last time.

I wasn't overjoyed about either of these, and while searching around for other options I found another of Ayende's posts (I think his blog is about 30% of the web... great stuff :)), asking for feedback on a more natural syntax for raising events from mocks. This looked a bit like this:

mock.MyEvent += EventRaiser.Raise(this, EventArgs.Empty);

I quite liked this, but there were a few complaints in the comments about subscribing to and raising the event at the same time. The post was from about 12 months prior to me writing this and, as I'm using a recent Rhino Mocks build and couldn't find it, it looks like nothing came of this. Let's look for a compromise that also fits in nicely with our Arrange - Act - Assert approach. First we'll see what we can get working based on the first, LastCall.GetEventRaiser() approach used:

[Fact]
public void Raise_event_with_new_arrange_act_assert_syntax() {
    //Arrange
    var mock = MockRepository.GenerateMock<IDoSomething>();
    var wasCalled = false;
    mock.SomethingDone += (sender, e) => wasCalled = true;
    
    var eventRaiser = 
        mock
        .Stub(x => x.SomethingDone += null)
        .IgnoreArguments()
        .GetEventRaiser();
    
    //Act
    eventRaiser.Raise(mock, EventArgs.Empty);

    //Assert
    Assert.True(wasCalled);
}

Here we are specifying a fairly useless stub so we can get an IEventRaiser. We are still using ye olde x.SomethingDone += null trick (albeit with a lambda to neaten it up), but we are pretty much stuck with that if we want strong typing on this as discussed at the beginning of this post.

I think this looks a bit more cohesive now we are using the lambda. We have one statement that is fairly obviously getting an IEventRaiser, rather than a null event handler floating around on its own confusing poor people like me :). Beyond aesthetics, this cohesion can let us pull out this functionality and start getting closer to a neater syntax. For now we'll just whack this in a .NET 3.5 extension method, but we could probably find a better home for it (it can go in a standalone class but the final syntax doesn't read quite as well to me).

public static class EventRaiserExtensions {
    private static IEventRaiser GetEventRaiserFromSubscription<TEventSource>(
        this TEventSource mock, Action<TEventSource> eventSubscription) {
        return mock
            .Stub(eventSubscription)
            .IgnoreArguments()
            .GetEventRaiser();
    }
    
    public static void Raise<TEventSource>(this TEventSource mock, Action<TEventSource> eventSubscription, object sender, EventArgs args) {
        var eventRaiser = GetEventRaiserFromSubscription(mock, eventSubscription);
        eventRaiser.Raise(sender, args);
    }

    public static void Raise<TEventSource>(this TEventSource mock, Action<TEventSource> eventSubscription, params object[] args) {
        var eventRaiser = GetEventRaiserFromSubscription(mock, eventSubscription);
        eventRaiser.Raise(args);
    }        

    public static void Raise<TEventSource>(this TEventSource mock, Action<TEventSource> eventSubscription) {
        var eventRaiser = GetEventRaiserFromSubscription(mock, eventSubscription);
        eventRaiser.Raise(mock, EventArgs.Empty);
    }    
}

The emphasised bit of code is the stub call we did last time, but this time pulled out into one method. The main bits are the Raise<TEventSource> extension methods, which combine all the steps and give us an easy syntax for calling an event on a mock based on an event subscription delegate. So our example now looks like this:

[Fact]
public void Suggestion_for_raising_events() {
    var mock = MockRepository.GenerateMock<IDoSomething>();
    var wasCalled = false;
    mock.SomethingDone += (sender, e) => wasCalled = true;

    mock.Raise(x => x.SomethingDone += null, mock, EventArgs.Empty);

    Assert.True(wasCalled);
}

The implementation itself might need work, but I reckon that syntax is pretty neat considering the limitations of C#. Of course, you're welcome to think otherwise, so please leave a comment expressing your outrage and/or contempt :).

Disclaimer: I am fairly new to Rhino Mocks (have tended to stick to manual test doubles) and especially to Arrange - Act - Assert (it's only in beta at present), so this might fail pretty hard in other circumstances. Still, I thought I'd post the syntax in case it gave more knowledgable people some good ideas :)

Tuesday, 27 May 2008

Top-down vs. bottom-up design

I've been having a think about top-down (a.k.a. outside-in) design during my recent iterative development exercise. In the series I've been putting off testing from the client layer down, primarily because GUIs have a reputation for being hard to test and harder to test-drive, and I wanted to make some early, easy progress on the core logic of the game.

I started to think that this approach might be a mistake. I'm dealing with the model that I think we'll need, not one demanded from the primary client of the model -- the GUI. Chad and Ben mentioned in their recent screencast that bottom-up implementation tended to lead to mistaken assumptions about infrastructure required by the top layers. I saw a similar point made on the BDD mailing list by Pat Maddox. Pat wrote (emphasis mine):

"I find an outside-in style of development to be very helpful... It forces you to think of your objects at a high level, so your design is driven by real need, and then you apply your design skills as you go on. When I use a pure bottom-up style, I write more speculative code and go down the wrong path far more often than I'd like. That's not to say that it's a problem inherent with that style, but rather a problem that I've personally experienced, and have more or less solved by using an outside-in approach."

This is opinion is echoed in an unrelated post to the TDD mailing list by Olof Bjarnason:

"I've been using TDD [bottom-up] for 2 years now, and it's been mostly a _great_ experience. The thing that bothers me most with "classic TDD" is that sometimes I build too much functionality in my classes, which isn't used in the end application after all. Even whole objects are wasted in the worst case."

The view here is that bottom-up design can lead to speculation and waste. By having a design driven directly by the overall, required behaviour, you only implement (and test) things that directly serve that behaviour. This can help eliminate speculative implementations of lower-level behaviour based on what you think the overall required behaviour will be.

Not so fast...

Sounds great! So what about inside-out / bottom-up / middle-out design? Ron Jeffries recently stated on the TDD mailing list that he generally prefers to start with the model (unless the project is simply to build a viewer). Maybe there's a bit more to it?

Digging further into that thread on the TDD list, there are a number of great points of view on the topic. Some TDD-ists argue that bottom-up design lets you build in small, easy steps, and refactor your way to the required behaviour that you would otherwise start with in top-down design. Others state that this leads to waste -- writing code and tests that just get refactored away. Which resulted in a couple of great quotes on the difference between refactored code and waste:

"I suppose we could also call the scaffold we use when constructing a large building as waste, or the safety harnesses as waste." -- John Roth to TDD list
"The analogy with scaffolding for a house is an excellent one - there is a lot of "stuff" constructed when building a house, *just* to support the construction - it is then discarded." -- Casey Charlton to TDD list

Top-down design can also lead to a "mockist" approach to TDD, where you need to mock all the required dependencies to implement the high level behaviour. This isn't necessarily a bad thing, but over-reliance on mocking can result in fragile tests. Martin Fowler has a great article on the pros and cons of "classic" and "mockist" TDD.

Enough rambling already!

While planning for part 3 of my recent development exercise I was coming to the conclusion that top-down was the way to go. After looking into it some more I was reminded of a whole host of advantages of bottom-up design. Even more importantly it reminded me that there is no silver bullet, and there are times when either, or a mix of both, approaches are fine. All this started to sound familiar, so firing up Google I noticed that I had read something to this effect in Jeremy Miller's excellent (as usual) post on the topic (search for "Bottom Up versus Top Down", although the whole post is worth reading).

I think the most important conclusion I've reached during this ramble is that if you are working in iterations to deliver a complete slice of the application (top and bottom) then you're never going to go too far wrong. Any "waste" from a bottom-up approach will be minimal as you'll be working toward and implementing the top almost immediately. And you'll still end up with higher-level behaviour specified with unit tests. Likewise starting top-down you'll still get the advantages of designing in small steps, particularly as you drive down into the design.

Friday, 18 April 2008

An assortment of basic TDD tips

I spent most of last week working strictly TDD-style on a work project. Now all the stuff I do at home is done using TDD, and I sometimes manage to test-drive a feature into a work project, but for a number of reasons I've never jumped 100% into test driving stuff for work.

For the first few days I had mixed results. The code and design was probably not significantly better or worse that I would have come up with without TDD. I did end up with a decent suite of tests for the code, which was a nice bonus, and the code took a similar amount of time to non-TDD for me.

The last couple of days were a very different story: I felt the code and design turned out significantly better and was written much faster than I would generally have done sans TDD. The whole process flowed wonderfully.

I thought I'd jot down a couple of rambling points I learned or re-learned during the week, for my own future reference and on the off chance I help someone else experimenting with TDD. These are all pretty basic points, but ones which I sometimes lose sight of while coding in anger :-).

When I'm not sure how to do something, my tests tend to drive the procedure instead of the design

This was something that occurred to me while test-driving some code to generate XML schemas (XSD). It had been a while since I had done anything manual with XSD, so while I knew roughly what what I was trying to do, I was not really sure of the details on how to do it. So I started writing tests about how I thought XSD worked, and responding to the feedback from those tests.

The end result was that my tests built up the procedure of how to generate XSD, rather than a good design for what I was trying to achieve.

While this can be helpful in itself to learn an API or something else that's a bit new to you, it is not what you really want for production code. So next time I'm in a similar situation I'll make sure I do a quick spike (possibly test-first if I think it will help) to learn how, before throwing it away and starting to test-drive the production code.

Avoid complex APIs until you really need them

Back to my previous XSD example, we have a few options as of .NET 3.5. First up, XSDs are just strings, so we could work at that level. They are also valid XML documents, so we could use XmlDocument, XDocument, or XmlWriter. Finally, .NET has a built in XmlSchema and related classes specifically for dealing with XSD documents. So which would you chose?

I started with strings, but quickly ran into the problem mentioned in my previous point: I had forgotten many of the details of XSDs that I needed to build up the right string. So I back tracked and jumped straight into XmlSchema, leaning on the API a bit to relearn everything. This introduced a lot of needless complexity into my design to enable it to play nicely with the API.

In retrospect I think I'd have been better off sticking with strings or another basic construct until I really needed a full featured API.

Have a clear Subject Under Test (SUT)

Especially when starting out with testing (any testing, not just TDD), I have occasionally managed to confuse myself setting up the test context -- the data and dependencies required for the test. I would sometimes end up testing the test data, rather than exercising the production code.

This is probably (hopefully?) a bit less stupid than it sounds, as sometimes your code will simply delegate to another object, in which case you can test the state (test data that comes back) or the iteraction itself (usings mocks).

It pays to be very concious of exactly what your Subject Under Test (SUT) is. I've found myself thinking increasingly in terms of the SUT, its dependencies, and its behaviour to be exercised in the test*. Once clear on these points, it's time to setup the dependencies to provide a specific testing context and test data, exercise the SUT, then verify that the SUT performs correctly in that context. Using a four-phase test structure can help here.

* I'm getting crazy ideas about single test contexts per class, where the test context becomes the class state. A bit like AMC but less to do with mocking and more to do with structure and easy reproduction of test context across related tests/specifications.

Use test difficulties to drive design

After completing a couple of tests on a class, I found there was a method that seemed like it should be protected, but that I still wanted to have tests around. There are lots of valid approaches to do this: using inheritance (either a test double, or self-shunt [PDF]), InternalsVisibleTo, generated mocks, reflection tricks, or just leaving the method public. But why should we have to go through these hoops just for testability's sake? Why is something so trivial requiring any complexity or workarounds?

This kind of signal is generally referred to as a "smell" -- something that just doesn't seem right, and it is this kind of feedback that TDD is very good at providing.

In this case the smell prompted me to have another look at the code, and I discovered that the method actually seemed to belong on another object. So I moved the method to the other class, and had the original SUT delegate to it. This meant I could test the now public method on its new class, while keeping proper encapsulation for the original class. And even more importantly, the design was now much cleaner and clearer (IMHO).

So if you come across something that seems a bit messier to test than necessary, it might be your test's way of telling you there is something amiss with your design. Sometimes you may look at it and decide it is worth a bit of mess, but other times it is a clear cue to refactor.

Use tests to drive through uncertainty

I was test driving a controller class that accepted requests for specific resources. I had tests for a VerifyAccess(Guid id) method which loaded some information about the resource with that ID, then ensured the caller had access. A few tests later and I had another method, GetResource(Guid id), which actually retrieved the resource. Now GetResource should really check the access as well.

//Pseudocode
public void VerifyAccess(Guid id) {
  //Get details about resource with id
  //Check access, throw if access denied
}
public Resource GetResource(Guid id) {
  //Get details about resource with id
  //Check access?
  //return resource
}

So I had the situation where both methods wanted to call each other. As the access verification logic was important, I also wanted to keep it testable in isolation from the code to retrieve the resource. It looked like a simple matter of extracting a private, helper method called from both methods, but I was not sure... there were a few ways I could do it, but the resulting method names and code structure all seemed a bit convoluted and unnatural.

My approach was to write a test that exposed the required behaviour. When doing something that calls GetResource, the attempt should fail if VerifyAccess would also fail. It was then just a matter of getting the test to pass.

My final implementation was much nicer than my initial, uncertain guess. Turns out that GetResource would be better suited as a protected method called GetResourceAndCheckAccess. Callers never actually had to get a resource, they only needed to use one. So the old tests around GetResource became tests around UseResource(Guid id) (I'm changing the scenario from the original problem as don't want to post work stuff verbatim, so the real names are a lot more natural. Hopefully the main idea is clear though). VerifyAccess also called GetResourceAndCheckAccess. I also ended up with a nice, private helper method, verifyAccessToResource(Resource resource), that took a loaded resource rather than an ID. The intention of the code was now obvious from the names and structure, and the tests acurately specified the required behaviour.

//Psuedocode
public void VerifyAccess(Guid id) {
  GetResourceAndCheckAccess();
}
protected Resource GetResourceAndCheckAccess() {
  //Get details about resource with id
  verifyAccessToResource(resource);
  return resource;  
}
private void verifyAccessToResource(Resource resource) {
  //Check access, throw if access denied.
}
public SomeOutput UseResource(Guid id) {
  Resource resource = GetResourceAndCheckAccess();
  return resource.DoSomething();
}

While it's obviously pretty simple to come up with a solution without going test-first, once the required behaviour was specified correctly and protected by automated tests, I found it much easier to work towards a usable implementation without having to worry about correctness all the time. Provided the tests stayed green, I knew the implementation satisfied the requirement. For me, this approach lets me focus on incrementally getting it right, without being distracted by the uncertainties caused by having many ways of proceeding to a "fina;" answer.

Hope this is of some help to someone. It was definitely helpful for me to explain it all in any case, so if you made it this far, thanks for listening! :-)

Monday, 25 February 2008

TDD is easy!

I've been following Jacob Proffitt's recent posts, which focus on challenging some of the conventional wisdom around TDD ([1], [2]. [3], cross-posted to TheRuntime.com). (At least, that is my guess at his intention. Alternatively he could just be trying to incite flamewars :)). I'm always happy to have my assumptions challenged, as such challenges can help lead to deeper understanding, so I've been careful not to dismiss Jacob's work and instead have had a good think about it all.

While I disagree with some of his assumptions, logic and conclusions, I definitely agree with the pointy-end of his argument: that plain old unit testing (POUT) without TDD is better than coding without any unit tests. This became especially apparent to me after reading Michael Feather's Working Effectively with Legacy Code, which helped me realise that once you had code under test, you can refactor and improve the design with not-so-reckless abandon, eventually bringing you to the nice, clean type of design that TDD aims to help you achieve in the first place.

Jacob suggests that the majority of benefits generally attributed to TDD are actually just benefits of POUT and good design principles, and because TDD is more difficult that POUT, the industry should focus on getting people unit testing independently of TDD. By focusing on this distinction between POUT and TDD, I started thinking about his assumption that TDD is more difficult that POUT. What is it about TDD that makes it so hard compared with POUT?

TDD itself is trivially simple: write a test, make it pass, refactor to improve the design. As far as processes go, that's dead simple. So why do people have trouble with it? Anecdotally, the kinds of problems I normally hear (and have experienced) are things like "How do I test code that relies on a database?", "How can I test this UI logic?", "How can I test this unit without setting up loads of dependencies?". There is a common thread to all these issues: "How do I test [X]?". Unit testing. POUT. Completely independent of TDD, people have problems designing testable software, and writing unit tests for their designs. Which is understandable: good design is hard.

So is TDD actually the easy part? Are POUT and general software design challenges the real sources of people's difficulties? Regardless of whether you use TDD or not, maybe the real challenge is unchanged: developing a good, testable design and writing effective unit tests for it.

If there is any truth to this then it does make a good case for TDD. The main aim of TDD is helping developers to get a good design that, as a side effect of the process, can be unit tested. Rather than increasing the barrier to entry for unit testing (or POUTing :)) as Jacob suggests, maybe TDD has the opposite effect by guiding developers to make better (or at least more informed) design choices. That's not to say that you can't get a good, unit tested design without TDD of course. It is simply to say that if you are having trouble with TDD, switching to POUT may not help you much. As you will still be facing the same design and testing challenges, but without the feedback provided by TDD, it might actually exacerbate the problem!

Wednesday, 6 February 2008

A brief look at the logic of TDD

[Test] 
public void Should_do_tdd() { 
  Assert.That(me.ShouldTdd, Is.EqualTo("Not sure?"));
}

Jacob Proffitt has a post questioning whether TDD provides any benefits over Plain Old Unit Testing (POUT). POUT itself has many benefits, many of which became apparent to me reading Michael Feather's Working Effectively with Legacy Code. In the comments on Jacob's post I said I thought it unlikely that TDD would be proved better than POUT, due to problems measuring, and even defining, software quality. Jacob replied that he wasn't interested in a proof, but was simply after the reasons why TDD might help. So I thought I would have a quick run through the logic of why TDD might help you write better software. I'm going to steer away from benefits of TDD that you can also get from POUT (like low coupling/high cohesion etc), and focus on the my interpretation of the rationale behind TDD.

Please note: I am not trying to convert anyone. I firmly believe that you should use what works for you. If a particular tool doesn't help you, don't use it. If you can't see any value from an approach and feel it is a waste of time to examine further, don't try it. I'm also far from an expert on TDD. But seeing as Jacob took the time to reply to my comment, I thought I should at least return the favour :-)

Quick TDD review

TDD is design tool/process. You write a test first that describes some behaviour that your production code should exhibit. You run the test and it fails because you haven't implemented that behaviour yet. You then write some minimal code that makes the test pass. Finally, you refactor the code to remove duplication and improve the design, re-running the tests to make sure you haven't broken the behaviour. This process leads to the TDD slogan: "Red, Green, Refactor", red and green being the colours of the status bar in most xUnit test frameworks to show failure and success.

So what?

What is the logic of that? Testing code that doesn't even exist yet? Crazy!

Well let's start with the obvious stuff. First up, you get unit tests. Unit tests are good, and let you refactor safely. POUT/test last obviously does this too. You get quick feedback on whether the code you have just written breaks anything. You can do this with a POUT approach as well, depending on how quickly you write your tests, or whether you use manual testing for feedback. TDD provides a bit more assurance that you will get the quickest possible feedback and will always have a decent amount of code coverage, but with sufficient discipline a POUT approach can accomplish all of this. And we trust our development team right? We don't need some process to force them to do the right thing.

TDD as a design tool

TDD is a tool for incrementally improving the design of your code. The unit testing side of it is simply a nice side effect, to the point where BDD has been proposed as an alternate presentation of the technique to eliminate the apparent confusion caused by the word "test". So how can TDD be used to improve design?

Well, first up you are specifying the exact behaviour you want to implement before writing the code to do it. This has several effects. You are writing the logical interface to your class before the class itself (interface, not public interface IInterface{}). This takes some of the guesswork out of determining how your code is going to be called. You have to deal with the interface to your class in order to test it, so if it is painful to use you can immediately tell and do something about it. According to my pseudo-logic, this can help ensure production code that needs to talk to your object should have a well designed interface through which to do so easily.

Specifying the behaviour you want first also helps focus you on one piece of code at a time. You are just trying to pass the test, not immediately trying to solve every problem the class will ever face. This can help reduce feature creep in your design. If you find that a "divide and conquer" approach can make problem-solving easier, then isolating the one thing you want to achieve in this way can also make coding easier.

If you have never written a class that exposes an interface that turns out to be fairly unusable in Real LifeTM, or if you have never worked for a while getting your class to handle a situation that will never actually occur (e.g. "What if this class needs to take a DateTime as an input instead of just ints?", followed by a large effort to produce a generic version of your class that is only ever called as MyClass<int>) then you are a much better developer than I (probably a given), and you may not get any benefit from TDD. TDD doesn't prevent these problems, but it can help make these problems immediately apparent and therefore potentially avoidable.

The refactoring step is an essential part of the design aspect of TDD. The idea is that you have just gotten your test to pass, so your class' behaviour for that specific test is correct. The very next step is to improve the design. Remove any duplication, extract any methods or rename variables as required to make the code more readable and understandable. Sprout any new classes that are required to better encapsulate the data or behaviour. Refactoring is not unique to TDD, but TDD helps you to perform these design improvements in small, hopefully easy, increments. If your test is difficult to write or implement, this feedback tells you your design might need tweaking, or that you initial specification needs more clarity. Your design is evolving based on continuous feedback from your immediate requirements and your actual code. This can help avoid large, difficult refactorings and unnecessary refactoring.

By improving the design at each step, in theory you make the next step easy to perform. The goal is having code that is always easy to change, making your more responsive to changes in business needs and requirements, and making bugs easier to fix (that's right! You still get bugs doing TDD! :-P).

Useless point on the "magic" of TDD

Aside from my convoluted version of the theory behind TDD, I feel TDD has the potential to change the way you think about coding. For me TDD had a profound effect on how I think about software design, to the point where even when not doing TDD I still find myself thinking in terms of passing tests and getting feedback from incremental coding steps. I feel this has made me a better developer, providing me with another way of thinking about problem. The extra perspective may not help you in every situation, or ever, but it does give you another avenue to pursue when you are stuck.

I also find I come up with much cleaner designs using this different perspective. The Robert Martin's Coffee Maker example [PDF] illustrates some OO design traps. In my experience the incremental design encouraged by TDD helps avoid some of those traps. Of course, this is all anecdotal hand-waving, hence this section's title :-)

Clarifications and conclusions

Refactoring, incrementally improving design, isolating behaviour, writing testable code, etc can all be achieved without TDD. TDD is just a tool to help you do all these things. If you do them fine without TDD, then TDD is probably not going to help you. If the technique sounds interesting to you, then your best bet is to give it a try and see if you see any benefits over and above POUT (I first got into TDD following this example. I converted it to C# and NUnit, commented out all but one test, and started coding).

I have not listed anything that is a dramatic, inspiring benefit of TDD. That is because TDD is simply a tool to help achieve what we are all trying to do anyway: writing good, well designed software. If you do that already then TDD may just seem like more work. This is probably why people that feel passionately about TDD can have a hard time selling it to people that are skeptical of it. It isn't dramatic. There is no "if you do this you will become almost as popular as Justice Gray" aspect to it.

I should also be clear that, for me at least, TDD did not come easy. I am definitely still learning, but my confidence and my results improve the more I use it. I feel it has been worthwhile. YMMV. If you have a mentor or a colleague to learn with this process may be easier.

As a closing aside, I think everyone will agree that at least people are debating the merits or TDD vs. a simple, good bank of units tests, rather than trying to justify the practice of unit testing itself. :-) Hopefully that means I won't ever have to face the "We don't have time to unit test" discussion again ;-)

Saturday, 12 January 2008

The contentious myth of Waterfall development?

Frans has finally had enough of the bickering on the ALT.NET lists. The last straw was when he mentioned the "W" word -- "Waterfall development", at which point he was allegedly set upon by a band of Kent Beck-loving, test-infected, over-zealous Agile thugs :-). Frans' main complaint (and probably a fair one) was the lack of evidence or science behind any of the arguments. Chad Myers had a good reply, where he used an industry example to try and show Waterfall development is fairly useless compared to iterative development.

All this reminded me of something I heard ages ago: Waterfall never really existed. I decided to have a quick look into it. First stop, Wikipedia, which states that the first reference to Waterfall-style development by Winston W. Royce in 1970 was in showing a model that was good in theory but flawed in practice. The purpose of his paper was to describe how the model could be fixed by adopting a more iterative approach. (He didn't use the term "waterfall", but he does use the familiar waterfall phase diagram.)

In the original paper, Managing the Development of Large Software Systems [PDF], Royce asserts that "the [Waterfall] implementation described above is risky and invites failure", his main complaint being that it takes too long to get feedback from testing and that any changes to design required become too disruptive late in the process. He then goes on to describe the steps to "transform a risky development process into one that will provide the desired product". Royce even concludes that the "simpler method [Waterfall] has never worked on large software development efforts."

This 2003 piece from Conrad Weisert has a bit more on the topic. His conclusion seems in rough agreement with Royce's: that phased software development is fine in theory and can work "when practiced with sensible judgment and flexibility" (or even agility ;-) ). But he is quite adamant that strict "Waterfall development", in which one never revists previous phases nor adapts to feedback from later in the process, does not and has never existed. This lends a bit of weight to Chad's view that strictly phased development processes "eventually devolve into necessary sub-standard Agile".

So according to my 5 minute, quasi-research, all this debate over Waterfall development is really just discussing a theoretical model presented over 37 years ago for the purpose of illustrating the advantages of iterative development. :-) Now can we all stop arguing about waterfall and get back to attacking people that misuse code comments please? :-)

Wednesday, 12 December 2007

ALT.NET manifestos

I have been following the ALT.NET group for a while now. The tech talk is great, although a lot of the threads get bogged down with topics around the group's identity, leadership, direction etc, which can become a bit distracting.

One of these posts was around Martin Fowler's suggestion that the group consider writing a manifesto to act as a guide for the community. I like the idea for the primary reason that it may cut through the identity crisis that keeps coming up in threads (and have lead to suggestions of splitting the group). I ended up suggesting one:

"We are a group of people who are passionate about improving the way we develop software.
We recognise there is no single solution, but instead there are multitudes of alternatives that can be applied to different situations.
Our community is a place for sharing these alternatives, so that together we can learn, teach, and encourage new ideas."

That pretty much sums up what ALT.NET is about to me -- constantly learning and finding new ways to improve the way we develop software. Whether these alternatives are TDD, BDD, DDD, IoC, MVC, mocks, WebForms, Silverlight, WPF, or carrier pigeon doesn't matter. The important thing is that people are talking about them and making informed decisions that suit them and their requirements.

I ended up getting a couple of positive responses to it, including from notables like Ayende, Justice and Bil (1, 2, 3). It'll probably get lost in the flood of posts to the group, but I like the idea that anyone can contribute and potentially make a positive difference.

UPDATE: This ended up on the ALT.NET wiki, thanks to Bil (until someone decides to remove it :-) ). Now if only I could make a contribution with my 1337 technical skillz instead of my Dilbertish mission statement generation abilities ;-)

Friday, 30 November 2007

Reflecting on JavaScript objects

I have been doing some more playing around with JavaScript recently, and wanted to do some reflection over JavaScript objects to see what functions they had, and then execute some of those functions. This is made fairly easy for us due to JavaScript's use of associative arrays (from Wikipedia's exampleobj.x = 10; is the same as obj["x"] = 10;).

First let's embed some JavaScript into a local HTML file:

<script>
  var MyClass = function() {}
  MyClass.prototype = {
    aFunction: function() { return 1; },
    anotherFunction: function() { return 2; }        
  }
</script>

Here we have a basic MyClass class. We can use the for..in statement to enumerate through the items in this class:

for (var member in MyClass) {
  document.write(member + "<br/>");        
}

This writes "prototype" (plus line break) to the page in FireFox (not in IE7, but haven't looked into why), which is the only thing defined for MyClass. You can also enumerate over MyClass.prototype to see what's there. In my case I wanted to check and run methods from an instance of MyClass (which is initialised from the prototype):

var instanceOfMyClass = new MyClass();
for (var member in instanceOfMyClass) {
 document.write(member);
 document.write(": " + instanceOfMyClass[member]());
 document.write("<br/>");
}                 

Which displays the following (in both FireFox and IE7):

aFunction: 1
anotherFunction: 2

Here we access the functions in instanceOfMyClass by looking up the value associated with each member. One quick gotcha: the for..in enumeration in this case returns strings, not pointers to the member itself (so you can't use member() to evaluate it).

Another option is to use the eval function to execute the method, but that isn't quite as pretty as it involves building up strings (eval("instanceOfMyClass." + member + "()")).

Note we aren't accounting for argument lists here. You might want to look at the Function class for getting more data about functions and their arguments. We also are not catering for members that are not functions. You can use typeof to filter out other values.

Monday, 19 November 2007

"There are no smart guys, there's only us"

Today's post is dedicated to El# (hi mate! :-) ), with whom I have had many conversations about this topic, with both of us facing the same issue from time to time. I've often talked about the quote from Jeremy Miller that titles this post, but I finally stumbled over the original source the other day:

Thoughts, Rants and Arguments: My DevTeach 2007 Rollup (search for "there are no smart guys" for the relevant paragraph)

I've sometimes been stymied by the thought that I just don't know enough to make a decision on a topic, and that I need to run it through a gauntlet of experts to get "the answer". This has bitten me when it came to introducing TDD, MVC/MVP web development, ORM, refactoring and other practices. I know the benefits, but how can I be confident enough to introduce one of these approaches without fully understanding the entire body of research on the subject, and without having an ironclad guarantee that it will work within a specific environment? I need to talk to the smart guys! I need "the experts"!

There is a big problem (ok, probably several problems) with this attitude. No one, not even the smart guys or the experts, knows "the answer". Generally there isn't "the answer" -- there are just a whole lot of options, some of which suck less than the others (and you won't know which is which without hindsight). There are no smart guys that know "the answer" and can solve all the problems, there's only us, so just make the best decisions you can as a professional. Some decisions will work and some won't, but don't expect anyone else to necessarily be any better in the same situation. As Jeremy Miller put it:

  1. No one's infallible and all knowing
  2. Don't sell yourself short compared to other people

Chances are the smart guys and experts we look up to and whose blogs we read are just the same as us. Maybe the only difference is that they are willing to take the chances, to risk failure, and to learn from everything. It's that kind of experience that makes you the smart guy or gal. If you want to be an expert, take exactly what you are doing right now and try some of the things that you previously were waiting on expert-approval for. Learn from it. Share it with your team or user group. Blog about it. As a former colleague of mine wrote (hi Hassan!), don't be afraid to make mistakes.

JP has had a number of recent posts related to these ideas, from the perspective of a well-respected expert, MVP, code jedi, superhero etc. To quote one of these:

(IsABlogger() && HasAnMVP() && HasDoneLotsOfPresentations()) != IsAnExpert()

By the way, none of this applies to ScottGu, who actually IS a smart guy and expert and should be deferred to at all times ;) (I'm being dead serious btw. How the heck does that bloke get across so much, and still have time to bag out Scott Bellware? :))

None of this is an excuse to make rash decisions or take uncalculated risks. It simply means that if you have put some work into an idea and genuinely believe it has legs, then run with it and see how it goes. Don't wait for the smart guys or the experts to validate it or give you the right answer. They're not coming. You all we've got. And you'll do fine :-)

Update 2008-02-07: Geoff Slinker has a fantastic post on a related note.

Wednesday, 7 November 2007

LINQ, deferred execution and closures

Reading Anders' post on Lexical Closures, Deferred Execution and Kicker Methods with respect to LINQ and Quaere, I thought I would write some notes since VS 2008 is RTM this month and I'll hopefully get to start doing some more LINQing.

I have used Anders' example. What result is printed?

int[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int i = 1;
var numbersPlusI = from n in numbers
                   select n + i;
i++;
foreach (var n in numbersPlusI) {
  Console.Write(n);
  Console.Write(" ");
}

To make the answer more obvious, let's rewrite without the layer of syntactic sugar. As I don't have .NET 3.5 handy on this PC, this is just an approximation built on .NET 2.0:

int[] numbers = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 
int i = 1;
IEnumerable<int> numbersPlusI = 
  Enumerable.Select<int>(numbers, delegate(int n) { return n + i; } );
i++;
foreach (int n in numbersPlusI) {
  Console.WriteLine(n);
  Console.Write(" ");
}

LINQ builds up an expression for numbersPlusI, but doesn't execute it until the result is enumerated. Now remembering that C# has closures, the delegate binds to the local variable i (not its value at the point of declaration). When the enumeration is being performed, the delegate is called using i, which is 2 at the time of execution (i=1; i++). So we get:

2 3 4 5 6 7 8 9 10 11 

If you want to run the code on .NET 2.0, here is my approximation of System.Linq.Enumerable and the Func<> delegate relevant for the example. Probably not brilliant, but I am really aiming to illustrate how variables a captured by closures in C#.

public delegate T Func<T, A>(A a);
public class Enumerable {
  public static IEnumerable<T> Select<T>(IEnumerable<T> source, Func<T,T> valueFromSource) {
    foreach (T value in source) {
      yield return valueFromSource(value);
    }
  }
}

Some good references on this:

Thursday, 1 November 2007

Double dispatch

Jeremy Miller recently had a post that mentioned "double dispatch", and I had to delve down into the dusty recesses of my at-best-mediocre brain to come up with a definition. Chances are everyone has come across double dispatch in one form or another, and understands it implicitly. However I find it harder to articulate the definition explicitly.

My (admittedly limited) understanding of double dispatch is that it chooses a method to evaluate based on the runtime types of two objects. Also, C# does not support double dispatch, but you can emulate it a number of ways by doing reflection tricks or by using a Visitor-pattern style approach. To illustrate the limitations in C#, I'll borrow the example from Wikipedia and collide some asteroids with spaceships.

[TestFixture]
public class DispatchBehaviour {
  public class SpaceShip { }
  public class GiantSpaceShip : SpaceShip { }
  public class Asteroid {
    public virtual String CollideWith(SpaceShip ship) {
      return "Asteroid hit a SpaceShip";
    }
    public virtual String CollideWith(GiantSpaceShip ship) {
      return "Asteroid hit a GiantSpaceShip";
    }
  }
  public class ExplodingAsteroid : Asteroid {
    public override string CollideWith(SpaceShip ship) {
      return "ExplodingAsteroid hit a SpaceShip";
    }
    public override string CollideWith(GiantSpaceShip ship) {
      return "ExplodingAsteroid hit a GiantSpaceShip";
    }
  }
  [Test]
  public void TestFailsWhenTryingDoubleDispatch() {
    SpaceShip ship = new SpaceShip();
    SpaceShip giantShip = new GiantSpaceShip();
    Asteroid asteroid = new Asteroid();
    Asteroid explodingAsteroid = new ExplodingAsteroid();
    Assert.That(asteroid.CollideWith(ship), Is.EqualTo("Asteroid hit a SpaceShip"));
    Assert.That(explodingAsteroid.CollideWith(ship), Is.EqualTo("ExplodingAsteroid hit a SpaceShip"));
    //This assertion fails:
    Assert.That(explodingAsteroid.CollideWith(giantShip), Is.EqualTo("ExplodingAsteroid hit a GiantSpaceShip"));
 
  }
}

The explodingAsteroid reference looks up the correct virtual function in the ExplodingAsteroid class despite it being referenced via the Asteroid type, thanks to polymorphism and virtual functions. But because C# uses single dispatch, the above test fails because based on the compile-time lookup of the giantShip reference (which is a SpaceShip reference at compile-time). If it where doing that lookup at run-time we'd have a different story.

One way of dealing with this is to switch on the type within the CollideWith methods.

public class ExplodingAsteroid : Asteroid {
  public override string CollideWith(SpaceShip ship) {
    if (ship is GiantSpaceShip) {
      return "ExplodingAsteroid hit a GiantSpaceShip";
    } else {
      return "ExplodingAsteroid hit a SpaceShip";
    }
  }
}
//...similar implementation for Asteroid.CollideWith(...)

This works, but if you end up with lots of different SpaceShip types then you are in for a hard time. If your group of asteroids is fairly static, you can use a Visitor-approach to accommodate lots of different spaceships. First we'll define an IAsteroid interface to represent the fairly stable group of asteroids, and an IAsteroidTarget as a Visitor, to represent anything that can collide with our stable group of asteroids:

//Element that accepts a visit, in Visitor pattern parlance
public interface IAsteroid {
  string CollideWith(IAsteroidTarget target);
}
//Visitor, in Visitor pattern parlance
public interface IAsteroidTarget {
  String CollideWith(Asteroid asteroid);
  String CollideWith(ExplodingAsteroid asteroid);
}

As our spaceships can "visit" the asteroid types, let's implement those next:

public class SpaceShip : IAsteroidTarget {
  public string CollideWith(Asteroid asteroid) {
    return "Asteroid hit a SpaceShip";
  }
  public string CollideWith(ExplodingAsteroid asteroid) {
    return "ExplodingAsteroid hit a SpaceShip";
  }
}
public class GiantSpaceShip : IAsteroidTarget {
  public string CollideWith(Asteroid asteroid) {
    return "Asteroid hit a GiantSpaceShip";
  }
  public string CollideWith(ExplodingAsteroid asteroid) {
    return "ExplodingAsteroid hit a GiantSpaceShip";
  }
}

Now comes the double-dispatchy emulation part. Let's make our asteroids accept visits from our IAsteroidTarget objects.

public class Asteroid : IAsteroid {
  public string CollideWith(IAsteroidTarget target) {
    return target.CollideWith(this); // <-- The double dispatchy part
  }
}
//Same implementation for ExplodingAsteroid : IAsteroid ...

The emphasised part of the code above delegates the way each target will be hit to the target itself. A slightly modified version of our original test will now pass:

[Test]
public void TestDoubleDispatchWorkAround2() {
  IAsteroidTarget ship = new SpaceShip();
  IAsteroidTarget giantShip = new GiantSpaceShip();
  IAsteroid asteroid = new Asteroid();
  IAsteroid explodingAsteroid = new ExplodingAsteroid();
  Assert.That(asteroid.CollideWith(ship), Is.EqualTo("Asteroid hit a SpaceShip"));
  Assert.That(explodingAsteroid.CollideWith(ship), Is.EqualTo("ExplodingAsteroid hit a SpaceShip"));
  Assert.That(explodingAsteroid.CollideWith(giantShip), Is.EqualTo("ExplodingAsteroid hit a GiantSpaceShip"));
}

Obviously there are disadvantages to this pattern. If you need to add more asteroid types things are going to be painful. (There are also much better ways of implementing this particular example of returning strings, but that is just due to its contrived nature. For a realistic example see Jeremy's post.) On the other hand, the process of adding targets is now trivial, even non-spaceship ones:

public class Earth : IAsteroidTarget {
  public string CollideWith(Asteroid asteroid) {
    return "Asteroid hit Earth";
  }
  public string CollideWith(ExplodingAsteroid asteroid) {
    return "ExplodingAsteroid hit Earth, causing the extinction of the dinosaurs";
  }
}

As an aside, this single dispatching behaviour of C# explains the cause of the generic overloading behaviour I mentioned before.

Finally, Derrick Coetzee has a good explanation of technical aspects of dispatching in C# with regards to the Visitor pattern.

Tuesday, 30 October 2007

Fluently constructing test objects

I have recently been playing around with TDD'ing a simple Pager control (like the one rendered at the bottom of the Google search results when your search returns multiple pages). For each test I ended up with a lot of recurring setup code (the typically repeated code is emphasised below):

[Test]
public void TestPagerAbbreviatesHeadOfList() {
  Pager pager = new Pager(2);
  StubPagerRenderer renderer = new StubPagerRenderer();
  pager.Renderer = renderer;
  pager.MaximumPageLinksToDisplay = 1;
  pager.CurrentPage = 2;
  pager.Render();
  string[] expectedPages = { "...", "2" };
  Assert.That(renderer.Pages, Is.EqualTo(expectedPages));
}

Traditionally a SetUp method has used to perform common initialisation tasks between test runs, but this practice is beginning to be discouraged, and after some initial doubts I am inclined to agree. I have frequently found my SetUp methods end up setting initial states that are overridden in some tests and not others, which quickly devalues the common initialisation and results in confusing tests (to assert something you need to check the SetUp method and check if the test is changing any of the default state). In fact, while I find I commonly need to setup common objects, most tests will require their own data relevant to that test. So does that mean I have to live with the duplication of the first 5 lines shown in the test above?

Well, being extremely prejudiced against duplication, I decided to create a method to create a new pager as a field in my fixture, with the relevant data passed in as parameters:

[TestFixture]
public class PagerBehaviour {
  private StubPagerRenderer renderer;
  private Pager pager;
  [SetUp]
  public void SetUp() {
    renderer = null; 
    pager = null;
  }
  void createPagerAndRenderer(int? currentPage, int? numberOfPages, int? maxLinksToDisplay) {
    pager = new Pager();
    renderer = new StubPagerRenderer();
    pager.CurrentPage = currentPage ?? pager.CurrentPage;
    pager.NumberOfPages = numberOfPages ?? pager.NumberOfPages; 
    pager.MaximumLinksToDisplay = maxLinksToDisplay ?? pager.MaximumLinksToDisplay; 
  }
  ...

I still used a very basic SetUp method here, just to force every test to explicitly recreate the pager (if they don't they'll get a null pointer exception -- I don't want a test accidentally using the state from a previous test). Here is what a revised test looks like:

[Test]
public void TestPagerAbbreviatesHeadOfList() {
  createPagerAndRenderer(2, 2, 1);
  pager.Render();
  string[] expectedPages = { "...", "2" };
  Assert.That(renderer.Pages, Is.EqualTo(expectedPages));
}

This has solved one problem, the duplication of the setup code, but hasn't solved the second, which is giving the test an obvious view of the Pager's state. How on earth am I meant to be able to determine the current page from createPagerAndRenderer(2, 2, 1)? Obviously this solution stinks pretty badly.

What I really want is an obvious way of passing the data, while still retaining brevity and minimal duplication. My current approach is to add a bit of complexity to get this by using a small class to build up the pager.

[TestFixture]
public class PagerBehaviour {
  private StubPagerRenderer renderer;
  private Pager pager;

  /* ... same SetUp() as last example ... */

  PagerAndRendererBuilder createPagerAndRenderer() {
    pager = new Pager();
    renderer = new StubPagerRenderer();
    pager.Renderer = renderer;
    return new PageAndRendererBuilder(pager);
  }

  class PagerAndRendererBuilder {
    private readonly Pager pager;
    public PagerAndRendererBuilder(Pager pager) {
      this.pager = pager;
    }
    public PagerAndRendererBuilder WithTotalPages(int numberOfPages) {
      pager.NumberOfPages = numberOfPages;
      return this;
    }
    public PagerAndRendererBuilder CurrentlyAtPage(int currentPage) {
      pager.CurrentPage = currentPage;
      return this;
    }
    public PagerAndRendererBuilder ShowingMaximumOf(int maximumLinksToDisplay) {
      pager.MaximumPageLinksToDisplay = maximumLinksToDisplay;
      return this;
    }
  }
  ...

My initial test now looks like this:

[Test]
public void TestPagerAbbreviatesHeadOfList() {
  createPagerAndRenderer().WithTotalPages(2).ShowingMaximumOf(1).CurrentlyAtPage(2);
  pager.Render();
  string[] expectedPages = { "...", "2" };
  Assert.That(renderer.Pages, Is.EqualTo(expectedPages));
}

True, this may classify as a bit of a misuse of a fluent interface, but to me it eliminates the duplication of creating the renderer and pager whilst providing an easy, readable way of passing test-specific data. The test only needs to deal with the initialisation that is relevant to it. The only cost is a slight increase in complexity, but to me this is more than offset by the increased readability.

Generics and overriding

Academic experiment of the day. I was interested to see how overriding works with generics. First let's take a quick look at how overrides generally work.

class BasicOverrider {
  public String DoSomething(Object obj) { return "Object"; }
  public String DoSomething(ICollection collection) { return "ICollection"; }
}
[Test]
public void TestBasicOverriding() {
  BasicOverrider overrider = new BasicOverrider();
  ArrayList someCollection = new ArrayList();
  Assert.That(overrider.DoSomething(5), Is.EqualTo("Object"));
  Assert.That(overrider.DoSomething(someCollection), Is.EqualTo("ICollection"));		
}

This test passes. In general, overriding picks the most specific match for your parameters. In the above example, ICollection is picked even though the ArrayList is also an Object. If we add another override that takes an ArrayList, that will take precedence over the ICollection and Object overrides.

Contrast that to overriding a generic method:

class GenericOverrider {
  public String DoSomething<T>(T someValue) { return "Generic"; }
  public String DoSomething(ICollection someValue) { return "ICollection"; }
}

If I pass in an ArrayList, which overload is called? Here is a passing test:

[Test]
public void TestGenericOverriding() {
  GenericOverrider overrider = new GenericOverrider 
  ArrayList someCollection = new ArrayList();
  ICollection sameCollectionAsICollection = someCollection;
  Assert.That(overrider.DoSomething(5), Is.EqualTo("Generic"));
  Assert.That(overrider.DoSomething(someCollection), Is.EqualTo("Generic"));
  Assert.That(overrider.DoSomething(sameCollectionAsICollection), Is.EqualTo("ICollection"));
  Assert.That(overrider.DoSomething((ICollection) someCollection), Is.EqualTo("ICollection"));
}

The test shows that to call a specific overload of the generic method, your parameters need to match the signature exactly, in this case ICollection, otherwise the generic method will catch it instead. This is due to the single dispatching mechanism in C#.

You can see this binding if you open up the compiled code with IL DASM. The ArrayList binds to the generic method (!!0), whereas the ICollection reference picks up the expected method.

IL_0028:  callvirt   instance string Workshop.UnitTests.GenericOverrider::DoSomething<class [mscorlib]System.Collections.ArrayList>(!!0)
...
IL_003f:  callvirt   instance string Workshop.UnitTests.GenericOverrider::DoSomething(class [mscorlib]System.Collections.ICollection)

Fairly academic I know, but might be of use if you are intending to have specific implementations over a general, generic method.

Tuesday, 23 October 2007

More on learning ReSharper

Moron learning? Yes, today I wanted to talk about how I am going about learning ReSharper.

A colleague of mine, after reading my last post on some basic ReSharper features, asked me how I'd learnt about these features, how much time it took, and whether there were any good tutorials out there.

Short version: printing keymap and playing around, not much, and haven't really looked. Of course, my verbosity knows little of and cares not for boundaries of any sort, so read on if you want the self-indulgent version.

The way I have gone about learning ReSharper it pretty simple. First I printed the keyboard shortcuts I find on the ReSharper documentation page (there is also a white paper there that covers the major features), and highlighted the ones I thought I would use regularly, and tried incorporating them into my coding sessions (Ctrl + Shft + R to open the Refactor This menu for example). Then I just had a quick look through the quickly-accessed ReSharper options whenever I had to do something "resharpery".

For example, if I had to do something that could potentially be done by an automatic refactoring, I would highlight the relevant section and hit Ctrl + Shft + R to see what refactorings ReSharper could offer, like extract a method, changing a signature, introducing a variable etc. I would also hit Alt + Enter whenever I saw the Quick Fix icon Quick fix icon, and had a look at the options provided.

I have learnt a lot, and continue to learn a lot this way. It has been a pretty low-intervention strategy -- it does not interfere with my normal work, but I still end up finding out a lot due to the easily discoverable nature of many of the ReSharper features.

If you want more in-depth tutorials there is the 31 days of ReSharper series (was for version 2.5 or so I think, but still relevant), and there are probably some more floating around the Net.

Wednesday, 17 October 2007

Getting to grips with ReSharper

On the couple of occasions I have talked people into trying JetBrains ReSharper (R#), the first thing they seem to notice is that it can optimise your using statements, and that it puts are bar down the right hand side of your editor showing you all the mistakes you have made in bright red and yellow stripes. There is obviously a lot more to ReSharper than that, and I've noticed people seem to get as much out of it as they put into it. Here are some of the features I found useful when I first started getting to know ReSharper 3.0.

Navigation

ReSharper introduces many nice ways of finding your way around your code. The File Structure View provides a list of all the members in your current class. Double clicking on a member jumps to that point in the code. You can also rearrange members and manage code #region blocks.

The mechanics of the File Structure View are fantastic, but to me the biggest advantage is the additional awareness it provides. At a glance you can take in all the members in the current file, which means you always have a good awareness of the context in which you are working, such as the class' current responsibilities.

I dock my File Structure View window to the right of VS and find it invaluable. You can access this window via the ReSharper >> Windows menu, or Ctrl + Alt + F.

Screen shot of File Structure View

ReSharper also provides a number of shortcuts to jump to a file, type, or symbol (Ctrl + T, Ctrl + Shft + T and Shft + Alt + T respectively). This lets you start typing part of the file/type/symbol you are looking for, and pops up an auto-complete box that allows you to quickly jump to the item you are after. Generally much faster than using Solution Explorer.

Other navigation features include an improved (over the standard VS) "Find Usages" feature, and a "Navigate from here..." menu that lets you jump to base, type declaration, function exits and more.

Code Generation

Mashing Alt + Insert opens a code generation menu, from which you can access wizards to generate properties with backing fields, constructors, interface implementations, and even delegations to class members. When I write "wizards", don't go picturing Clippy or some equivalent monstrosity -- these are actually helpful! For example, the constructor generator lets you select the fields/properties you wish to initialise in the constructor's parameters and then dumps the constructor into your class. The wizards are generally very keyboard friendly as well, so you don't have to madly chase your rodent around trying to click obscure buttons or links.

Generate constructor screenshot

Templates

The templates in ReSharper are incredible. There are a couple of templates build in (try typing "foreach<TAB>" into a method that takes any IEnumerable like an array as a parameter. No really, go try it! I'll wait...), but the real power comes from creating your own Live or Surround With template.

The templates support parameter substitution (i.e. you put a token in your template), and through the template builder UI you can specify exactly how these parameters are populated at run time. For example, you can tell ReSharper to guess the substitution based on the current type, current parameters, or even transform an existing name (such as using the camel-cased version of a Pascal-cased property name).

Edit template example

The educated guesses ReSharper uses are generally spot on, and are used in a number of places throughout the product, such as some of the Quick Fixes.

You use a template by typing part of the name into VS, and selecting the template from the autocomplete menu that pops up.

Refactoring

The standard Visual Studio refactorings are awful. On every PC I have used it has been almost entirely unusable. Trying to rename a private class member tended to cause a complete recompilation of the entire solution and basically take an eternity. ReSharper's refactorings work in milliseconds, and provide a whole lot more than VS.

The standard ReSharper 3.0 keymap (not the IntelliJ/ReSharper 2.x one) lets you mash Ctrl + Shft + R to open a context-sensitive refactoring menu. For example, if you highlight a passage of code and hit Ctrl + Shft + R, you can choose Extract Method to move that code to its own method. ReSharper will either instantly apply your refactoring, or open one of its helpful wizards if it needs a bit more data from you to continue.

There are also several chords you can press as short cuts to various refactorings, like Ctrl + R, Ctrl + V to apply the Introduce Variable refactoring. The refactoring features of ReSharper are extremely powerful, but in my experience require the most amount of work to learn how to use effectively. Every day I seem to find a new way to use a ReSharper refactoring to make coding easier.

The screen shots below show the "Refactor This" menu that appears after a value is selected and Ctrl + Shft + R is pressed. The second shot shows the Introduce Variable wizard, and the third shows the result.

Refactor This context menu

Introduce variable refactoring example

Result of introduce variable refactoring

Intellisense improvements

ReSharper, depending on which options you have specified (ReSharper menu >> Options), augments the standard Intellisense offered by Visual Studio. One option I turn on is to show more info about members, such as the return types. It is a good idea to play around with this to best suit the way you work.

The main thing ReSharper offers in this area is smart autocomplete and type autocomplete. Instead of the default Intellisense triggers such as Ctrl + Space, you can press Ctrl + Shft + Space or Shft + Alt + Space to get ReSharper to intelligently restrict the autocompletion options base on your current context. For example, if you are initialising a variable from a method call and and trigger a type-autocomplete, ReSharper will only show you a list of methods that return a compatible type.

Quick fixes

This is the best feature in my book. Whenever ReSharper finds an error, a suggestion, or recognises a number of common actions in the current context, it will flash up a light bulb and underline the relevant code. The colour of the light bulb and underline will depend on what type of quick fix ReSharper has identified (error, suggestion etc).

When you see Quick fix icon, press Alt + Enter to open the Quick Fix context menu, which will solve all your problems for you.

An example that is really useful when doing TDD is when you write some test code first that does not yet exist. The missing method will be written in red, and the quick fix icon will appear. Pressing Alt + Enter will display the menu shown below:

Quick fix menu to create a method

If you select "Create method...", a method stub will be generated, and you can TAB through the fields in the template ReSharper uses and fill in the details. The scree