Pluralsight blog Where devs, IT admins & creative pros go for news, tips, videos and more.
3,500+ tech & creative courses authored by experts - unlimited & online Get it now →
January 16, 2014

Identify code smells with Visual Studio Code Metrics

By image4

When you first start writing code for a new program, the possibilities are endless. There are no bugs, the slate is clean, and there are no issues with organization or complexity to deal with. However, as the software evolves and has to actually do something, parts of it will show signs of design neglect. Maybe a responsibility is misplaced in one class. Perhaps a name isn’t as descriptive as it could be. A little duplication here, some inconsistency there. As you grow in experience as a programmer, you start to notice these attributes of your codebase that make it more difficult to work with, even if the code itself is functionally correct. Kent Beck dubbed these “bad smells in code,” or code smells, and once you’re able to recognize them, you can make informed decisions about when and whether it makes sense to clean up your code with some refactoring.

Long methods

There are many different code smells, but long a method is one of the most common and easily corrected code smells. A long method is any method that is so long it is difficult to understand at a glance.  Different individual programmers will have different opinions about how long is too long, and I don’t believe there is a single rule that would apply in all cases. However, in general you should prefer methods that are shorter to those that are longer, methods that do only one thing and methods whose length permits them to be viewed on a single screen in their entirety. Methods should also have descriptive names, and if their name starts to read like “DoThisAndThatAndSomethingElseAndAnotherThing” then that’s probably an indication that it’s doing too much.

Finding long methods in your project is actually pretty easy to do using Visual Studio’s analysis tools. In Visual Studio 2013, while you have the project you want to analyze open, click “ANALYZE” then “Calculate Code Metrics for [ProjectName].”

Figure: Calculate Code Metrics for the CodeSmells project.

You’ll be able to view the results in the Code Metrics results window, which by default is listed in a hierarchical view by project, namespace, class and method. The various metrics are aggregated. For instance, at the class level you’ll see the total lines of code for the class, while at the method level you can view the method’s lines of code.

Figure: Code Metrics results in Visual Studio 2013

In the figure shown here, I’ve highlighted one method that’s particularly bad, with 28 lines of code and a cyclomatic complexity value of 19 (ideally should not exceed ten). While 28 lines of code may not seem like that many, it’s important to realize that Visual Studio is only counting logical lines of code.  The actual text of the method, which contains no comments or whitespace, is 114 lines long. You can see a high-level view of it here:

Figure: A long method example with a high cyclomatic complexity

Refactoring

To clean up code smells, one must refactor. Refactoring is the process of improving the quality of the code without altering its external behavior. In the case of the long method smell, the most common way to refactor is to extract methods from the long method. In this way, the method can be broken up in to a collection of smaller, more cohesive (and probably better-named) methods. In general, the extract method refactoring is one that can usually be done with the assistance of built-in tools in Visual Studio. For example, in the code above, there is only one line block that is responsible for decrementing the Item’s SellIn property. This could be extracted into its own method like so:

Figure: Highlight code to extract, choose Refactor -> Extract Method

Figure: Provide a name for the new method

Figure: Refactoring completed


Using Excel

If you want to quickly identify the longest methods in your project or solution, simply sorting the Code Metrics results window won’t necessarily work, since it will include the namespaces, classes, etc. However, you can easily export to Excel by clicking the Excel icon in the toolbar. Once there, it’s easy to filter and sort on just the method values (called Member). Specifically, under “Member,” choose “Text Filter” then “Does Not Equal” and leave it blank to indicate that you only want values that are not blank.

Figure: Add a Text Filter to Member to view only Methods

Then to sort by lines of code, just click its dropdown and choose “Sort Largest to Smallest.”

Figure: Sort by Lines of Code, descending

The result should list all of the methods in your project or solution, sorted by their lines of code, descending. This is a great way to identify which areas of your code are in most need of refactoring. You can also do the same with cyclomatic complexity or Visual Studio’s Maintainability Index (which combines several metrics and produces a single value on a 0 to 100 scale, with higher numbers being better).

Bad smells in your code can make it more challenging to work with. Clean up smells like long method using refactoring techniques such as extract method. Visual Studio’s analysis and Code Metrics make it easy to find the longest methods in your codebase, so use these tools to identify the places where you’ll get the most benefit from spending a few minutes on code hygiene. Your fellow programmers and your future self will thank you.

To learn more about refactoring, be sure to check out Steve Smith’s Refactoring Fundamentals course in the Pluralsight library.

About the Author

is an Executive Vice President of Services for Telerik. Telerik Services provides consulting, training, and other services to Telerik’s enterprise clients and partners. Steve is also a Microsoft Regional Director and MVP, as well as a frequent speaker at software developer conferences and events. Steve has (with his wife and partner Michelle) started and sold a number of businesses in his career, including one of the first online developer community websites (ASPAlliance.com), the first Microsoft developer advertising network (Lake Quincy Media), and a successful agile consulting company (NimblePros). Steve has written or contributed to a number of books, most recently 97 Things Every Programmer Should Know.

Author's Website: http://ardalis.com


Discussion