Rickard Nilsson is a software architect, developer, craftsman, agile enthusiast, and father of three... More
Rickard blogs about crafting software using .NET tooling and solid, development practices.
This is part of a series of ReSharper Ninja ticks and workflows which I’ve picked up over the years. This particular one is brand new in ReSharper 7.
Category: Refactoring
This is a new feature in ReSharper 7 and one that I and many with me has been missing for a long time. Previously when you had a class with too many responsibilities, you had to go through a lot of hoops with ReSharper to refactor the code into cohesive units, and it usually involved a few manual steps.
Now, in version 7, we have an option on the refactoring menu called Extract class which automate the procedure. You place the marker on a class member and hit Ctrl+Shift+R to bring up the refactoring menu, and choose Extract class. This gives you a dialog where you can pick which members should be extracted and ReSharper analyses dependencies between different members such that the code won’t brake after the refactoring.
Checkout Hadi Hariri’s presentation on Extract Class at 07:28
I’ve been a heavy ReSharper user, fan, and addict since I first tried it back in 2007. Over the years I’ve developed the way I code leveraging the powerful productivity features of ReSharper and Visual Studio.
I present a series of my favorite Ninja tricks and workflows to inspire others to improve their skills and I encourage you to do the same, either in the comments section or elsewhere.
You can find this and other power tips with the ReSharper user tip tag
Category: Workflow
Following test-driven development I often define my unwritten classes by first using it in a unit test. I then use Create class and Create method or property to generate the code from usage. As the class gets created in the same file as the unit test I use Move to folder to put the class in the production code assembly. Namespaces and using statements are fixed automatically.
Place the marker on the class name in red and hit Alt+Enter
Place the marker on the method name in red and hit Alt+Enter
Place the marker on the class name and hit Ctrl+R, O. Then pick the folder you want the class to move to.
TDD Katas has become very popular in a small segment of the development community and we call our selves software craftsmen. We are passionate about software development as a craft and engage in different activities to better our selves and our peers.
My first kata cast, for instance, has been viewed close to 10k times on Vimeo since its publication. Much of the attention is of course due to Roy Osherove linking to my blog post from his TDD Kata 1 page. This time Roy initiated a sequel, meant to introduce interaction based testing using mocks and possibly stubs, and continue the teaching process of TDD and unit testing practices.
The following screen cast covers the entire kata in .NET, complete with Osherove’s three steps as well as manual UI testing at the end.
For best viewing experience I recommend watching it on Vimeo.com in HD
String Calculator TDD Kata 2 - Interactions from Rickard Nilsson on Vimeo.
The tools I use are Visual Studio, ReSharper, TestDriven.NET, Moq for mocking, and NUnit.
The code and Visual Studio solution for the finished Kata can be downloaded from GitHub:
Download source
As Osherove mentions in his instructions, this kata is not as simple as the first part, nor as simple as most katas out there. The reason is the element of interaction based unit testing involved, which is quite difficult to wrap you mind around, and it took quite a while to get the steps right. I thought I should share my path to the kata in its present form for others to learn from and comment on.
Step 1. Everytime you call Add(string) it also outputs the number result of the calculation in a new line to the terminal or console. (remember to try and do this test first!)
As I did this test first I started out pretty much as how it ended up in the cast. However, after a while I tried to take a step back and see if there were any smells in the code I had not yet discovered.
I found that I didn’t really like the mixed responsibilities that the Calculator class got when I introduced writing to the console. This could be seen as a logging feature and thus a perfect candidate to become an aspect (in AOP). I started playing around with PostSharp and ended up with the following solution which is quite clean.
[Serializable] public class OutputAttribute : OnMethodBoundaryAspect { [NonSerialized] private IContainer container;
public override void OnExit(MethodExecutionArgs args) { var console = container.Resolve<IConsole>(); console.WriteLine(args.ReturnValue.ToString()); }
[OnDeserialized] public void OnDeserialized(StreamingContext context) { container = ContainerFactory.Current; } }
Which, at most, leaves the mark of a custom attribute in the Calculator class:
public class Calculator { [Output] public int Add(string value) { ... } }
The problem with this solution is the way PostSharp works. It does all its magic as a post compilation step so everything is pretty much static. This is a problem in a testing scenario when we need to inject the mocked console in this case, hence the smelly ContainerFactory.Current stuff.
Another problem with this solution is that in part three, the console app, we need to disable or override what is outputed. This ends up becoming a static mess which did not feel right at all. If you have another view on this please leave a comment.
Step 2. Create a program (test first)that uses string calculator, which the user can invoke through the terminal/console by calling “scalc ‘1,2,3’” and will output the following line before exiting: “The result is 6”
For step 2 and 3 I thought a bit about refactoring to a UI design pattern like MVP, MVC or MVVM but finally decided to drop it, mainly because I didn’t know any framework like that for console applications. If the application grows I think this is the right way to go, but for the known requirements it’s an overkill, especially considering how small the solution is.
Step 3. Instead of exiting after the first result, the program will ask the user for“another input please” and print the result of the new user input out as well, until the user gives no input and just presses enter. in that case it will exit.
I played around a bit with SpecFlow, which has ha free form Given/When/Then specification syntax, on the later part of the kata. However, I felt that I lost velocity so I dropped it as well. Maybe, if I had some way of conducting complete acceptance testing through a real console, I would have pursued this further. It was simply too much to write, for example:
Scenario: Prompt user for another input Given a new string calculator And the user has entered: a valid input When the program has outputed The result is 1 Then the user is prompted for another input Scenario: Quit on empty input Given a new string calculator And the user is prompted for another input When the user hits enter Then the program should exit
Scenario: Prompt user for another input
Given a new string calculator
And the user has entered: a valid input
When the program has outputed The result is 1
Then the user is prompted for another input
Scenario: Quit on empty input
And the user is prompted for another input
When the user hits enter
Then the program should exit
Figure 3. SpecFlow Feature specification for the console app If you have any thoughts, comments, suggestions, or any other feedback please leave them below or ping me on twitter.
Are you new to the concept of code katas? Read my previous blog post and watch me perform the String Calculator Kata.
In my never ending goal of self improvement in the techniques and tools I use I’ve been practicing a version of the Prime Factors Kata for a while.
The Prime Factors Kata, initially sparked by the infamous Uncle Bob Martin, is about finding an arbitrary number’s prime factors. In the cast I show how my TDD practice has evolved into a flavor of BDD, mainly to reduce duplication in the unit tests. I also show off the awesome power of my current toolset which includes the Visual Studio 2010 and the latest versions of ReSharper, TestDriven.NET, NUnit and NBehave.
Though my performance is not yet perfected I want to put it out there because I feel there are no C# version that can really match the Ruby version in elegance and wit. This is my attempt to show what you can do with the C# language when you know the frameworks really well.
Please leave comments and/or suggestions below or record your own kata session in response.
Prime Factors Kata in C# from Rickard Nilsson on Vimeo.
If you are new to the Prime Factors Kata, code katas in general, or TDD for that matter, you may find the steps I take unnecessary or weird. You may want to watch the annotated version in which Uncle Bob explains why each step is taken and why they are taken in that order.
Many have recorded there own versions of the Prime Factors Kata which all inspired me in the way I practice it. The cast that inspired me the most is
there are also a few other C# casts worth watching for comparison by:
Have you ever come across the concept of a Code Kata?
For me it really took off after reading blog posts (1, 2, 3) by Unce Bob Martin and Pragmatic Programmer Dave Thomas. The concept is really simple: how can we, as programmers, better our selves and improve our techniques and proficiency in using the tools and processes in our every day work?
The suggested solution is inspired by the martial arts kata. You learn how to implement a solution to a specific problem and you practice all the moves in the exact same order over and over again. The point is that you should know the moves so well that you forget about them and focus on improving your key strokes and the use of your tool set. The never ending goal is to perform the kata with the least amount of key strokes.
The promise is that practicing these kata's often and regularly makes you a better and more productive programmer in that you are trained to act instinctively in certain reoccurring situations.
Anyway, I've been practicing a kata based on a problem initiated by Roy Osherove and I decied to record it to get some feedback and maybe spread some knowledge on how I practice Test-driven development using ReSharper.
Calculator Code Kata Cast 1 from Rickard Nilsson on Vimeo.
Update! You can now find more user tips with the ReSharper user tip tag.
Have you ever wanted to rename a namespace but you have too many classes in the namespace that it would be an infeasible hassle changing all of them individually. Even using a tool like ReSharper to refactor the namespaces class by class is a hassle. Here is how to rename a namespace for all of its classes in a couple of key strokes using ReSharper.
Update! Alternate context menu option to rename namespaces. Tested with ReSharper 5.1.
and you're done!
Please leave a comment if you found this useful.
* Visual Studio scheme
I've been using Jetbrains ReSharper a while now and I love it. I can't even imagine going back to plain Visual Studio anymore because there are so many things in my daily work that involves ReSharper, even simple tasks like editing source code and navigating through code and source files, let alone creating files and running unit tests.
Now I want to share a user tip I found that isn't obvious to find nor part of any context menu. It's actually a refactoring and I call it Magical strings to variable. You can use it when you end up with multiple equal string literals in a piece of code. You would probably want to gather all of the string literals in a variable and reuse it through out the code. You can use ReSharper to do it for you in a couple of key strokes.
[Test]
public void ParentPresenter_Update_should_update_view() {
var model = new User {
Name = "foo"
};
using (mockery.Record()) {
Expect.Call(parentView.Username = "foo");
}
using (mockery.Playback()) {
IParentPresenter presenter = new ParentPresenter(parentView) {
Model = model
presenter.Update();
Assert.That(presenter.Model.Name, Is.EqualTo("foo"));
var name = "foo";
Name = name
Expect.Call(parentView.Username = name);
IParentPresenter presenter =
new ParentPresenter(parentView) {Model = model};
Assert.That(presenter.Model.Name, Is.EqualTo(name));
1. Highlight one of the string literals
2. Press Ctrl+R, V (Ctrl+Alt+V)* to introduce a variable
3. Select to replace all occurrences (default option)
4. Pick a name for the variable
..and you're done! Please leave a comment if you find this usefull.
* Visual Studio scheme (ReSharper 2.x / IDEA scheme)