Thursday, August 30, 2012

Rocking the SRP with ReSharper

The Single Responsibility Principle is a pain in the ass. You're trying to get something done, and don't have a lot of time, and you'd like to keep all the moving parts in front of you. So put it all in one class, or better, yet, one method.

Messy desks can help you think, but at some point, they start to look like this:


And that's when you realize you need that bit of code that did some piece of magic for another control, but you can't remove it without three feet of paper falling on the floor. I know. I've lived it. This week.

So the second time I needed my store-some-form-variables-in-session-while-I-make-somebody-log-in code, I got smart. I didn't write it. I pretended it existed. I gave my imaginary friend an impressive name, LoginHandoffUtil, and started slapping methods on the sucker. Sure, Visual Studio got mad, and put the class in  fire-engine red, but I didn't pull the trigger on creating it just yet. I was in a groove, and didn't want to hand the controls over. That's when ReSharper freaked me out. Because its tricked-out Intellisense started giving methods that I just made up, that didn't yet exist. Sure, they were screaming red, but they were there, at the click of a dot. Nice.

So I've got my consuming code written, and now I'm autogenerating class and method stubs. But I'm keeping the class in front of me, in the same code file. Consuming code up here needs something, so add it to the Util class down there. All in front of me, on my big messy desk, until I've got the thing working. Messy, but the new class is doing just one thing, just as Uncle Bob would like.

When it's time to go home, you should think about cleaning up your desk, maybe putting some papers in the trash, and the ones you need to keep in your files. So have ReSharper put the class in its own file. Presto, you have a nice small class that does just one thing. But where should you put it? Next to the consuming ASCX files, or in some Util folder somewhere, maybe even in a separate project? No worries, if you decide to move it later on, ReSharper can update namespaces to be consistent with the new location, while updating consuming references, so that your code still works.

The best part of the story was coming in the next day, tackling the next step in the project, and my new little class just worked. Bliss.



If you're interested in trying this out, there's a nice ReSharper video on using the tool for code generation while doing TDD.  Soon, you'll be using Alt+Enter to make classes and methods appear, without touching your mouse.

No comments:

Post a Comment