The fastest way to sexy code using Visual Studio

Here it comes.

Another spicy new update to Visual Studio.

And yet, it’ll come and go and I’ll most likely continue using the same damn subset of features I’ve gotten used to for years.

Same as you, right?

Code highlighting, Find By References, and Go To Declaration. A glorified text editor with enhanced file search.

It takes time and deliberate effort to learn a new feature, let alone implement it regularly enough that its true value is realized.

Time we just DON’T have.

Which sucks because there are treasure troves of wizardy hidden beneath Visual Studio’s hefty mass that could improve our code, our software overall, and make us better devs in the process.

But there is one feature that you don’t have to look too deep to find.

One that will massively boost the quality of your code.

In this article I want to share with you not only the Extract Method refactoring feature, but also how to perform it at lightspeed, and how to use it most effectively, hopefully resulting in a surge of brilliantly clear code from your fingertips and immense gratitude from your teammates and future developers.

Did I sell ya on it?

Readability: an aside

Before we jump in to the technicals, let’s back it up with a bit of context.

Code readability is a human factor.

We strive to make our code as readable as possible, often over all other considerations, so that the next developer (which could be you) has the best possible chance of understanding what it does and what you intended.

Despite code being the literal manifestation of pure logic, it is still an exhausting endeavor for any human to decypher for too long.

For that, we compose our code to be more like prose in a book.

Its algorithms, object interactions, and architectures ideally can be read aloud to a senior dev, an intern, and a business analyst, making up a coherent ubiquitous language, as they say in the DDD world.

With this in mind, I believe liberal use of clearly named methods is the easiest way to improve readability in our codebases.

Clearly named methods can be added both at the time of development, or during refactoring.

I often like to write an algorithm first, then decide after how it will be composed and named.

This is where the extract method refactoring joins the party.

The way of the sloth

The extract method refactoring simply means moving a block of code into a new method, and then calling that method from the original location.

Replacing code with a method.

Now, you could do this manually by creating a new method, highlighting, copying, and pasting the code block into that method, then deleting that original block and replacing it with the method call.

It was exhausting just typing that…

Below we can see that strategy in action on a particularly chubby method that binds a view model representing a quote for a loan to the fields of a web page.

Don’t feel bad if you still do it this way. It’s tried and true. I did it this way for the first 7 years of my dev career.

The slightly faster, mouse-clicker strategy

The next bump in skillset comes when you realize Visual Studio has built in refactoring tools that make extracting methods a lot faster.

You can find the extract method shortcut three different ways: first by highlighting a block of code, then either waiting for that little yellow lightbulb (or blue screwdriver) icon to pop up and clicking it, right-clicking inside the highlighted region and selecting “Quick Actions and Refactorings”, or clicking CTRL+. to summon the suggestions manually.

Below you can see me demonstrating the right-click strategy.

Yep, juuuuust fast enough to let me demo two method extractions instead of one!

Now let’s go one final step to mastery.

The way of the superior developer

The final step to take us to light-speed, boss-ass bitch mode is to map the extract method feature to a keyboard command so you can finger-flick your way to readable code in under a second.

To do that, (open up VS and do it right now), go to Tools -> Options -> Environment -> Keyboard.

Filter the commands by typing “extract” and selecting the Refactor.ExtractMethod command.

Selecting “Text Editor” in the Use new shortcut in dropdown so that the command only applies when the text editor is in context.

And finally, typing the key command you’d like to use and selecting the Assign button and clicking OK.

You’ll want to choose a command that is easy for you to type quickly and comfortably (so that you remember it and use it.) I type using the Dvorak keyboard layout, so CTRL+; is the same as typing CTRL+Z on QWERTY, making it a quick flick of my pinky and ring finger.

Once that’s in place, try it out! And practice it so you don’t forget it.

Oops, went so lightning quick I misspelled producer!

Now, I have to say, it’s not wise to go this fast, but you get my point. The faster you can perform something, the more likely it is that you’ll use it.

Psssst! Know anyone who might want to read this? reddit linkedin Click to share to: google+

Okay, now we’re playing pro level, but how can we use this new skill most effectively?

What I mean when I say liberal use

To close up, I’ll leave you with a few tips for improving the readability of your code.

1) Don’t be shy.

I would almost go as far as saying you can’t have too many methods. Readability > method count in my book.

On occasion, I will leave a method somewhat big instead of breaking it into several smaller methods, usually because I determined that seeing all of the logic on the screen at once was more comforting and allowed better reasoning, but this is a rare occasion.

You can even be as bold as to convert a single line of code into a method call if the method’s name is easier to understand than the statement alone. This works especially well with multi-conditional branching statements.

For example, what reads better?

This?

if ( vehicles . Sum ( v => v . Price ) < loan . AmountRequested && Settings . IsExcessFundingAllowed ) { //fund excess amount... }

Or This?

if ( IsLoanFundingExcessAmount ) { //... }

Methods also give you the opportunity to speak in the language of the business. The second example is easily understandable to all parties, whereas the first example needs a few more mental clock cycles to parse and understand, even by a developer.

The easier it is to understand, the easier it is to change in the future.

2) Pay attention to blank spaces.

Whenever I add a blank space, it’s usually to signify a new grouping of logic, just like paragraphs in an article.

Often times you can replace that grouping with a single method call that reads better than the grouping does in its raw state. The example in the animated GIFs above show this idea in action.

3) Create composed methods as a first line of defense

Notice in the example above how we composed a large method into several smaller ones. This is called the composed method refactoring, and it’s a great way to bring greater understanding to an algorithm or class. It’s much easier to understand a small bundle of clearly named methods than a blob of seemingly random statements.

It’s kind of like pruning a tree or picking weeds. Keep methods from growing in size by composing them into smaller ones as soon as it makes sense.

Practice, practice, practice

Alright, new skill in your pocket, now all ya gotta do is use it a few times until it that finger flick becomes muscle memory.

The extract method refactoring feature is easily one of my top three favorite and most used features, so I hope it brings some value to you and your team.

If you found this helpful, I’m going to be creating one new practical Visual Studio tip per month for the next 6 months.

It’ll be a mix of old (yet hidden) tools and brand spanking new tools, but only things I actually use regularly. If you’d like to skill-up with more power tools like this one, join my list below and I’ll email them to you as they come out, along with two to three other emails per month on related helpful articles and essays.