Click here to Skip to main content
Click here to Skip to main content

Coding Standards and Code Reviews in Visual Studio .NET

Defining coding standards and establishing a code review process can be time-consuming and challenging. This article explores techniques for doing so, focusing on creating practical standards and automating code reviews when possible.

Editorial Note

This article is in the Product Showcase section for our sponsors at CodeProject. These reviews are intended to provide you with information on products and services that we consider useful and of value to developers.

This is a showcase review for our sponsors at CodeProject. These reviews are intended to provide you with information on products and services that we consider useful and of value to developers.

Introduction

Few topics in the discipline of software development ignite more debate than coding standards. Discussions range from seemingly innocuous topics such as formatting and commenting practices to those debated with religious zeal, like the use of Hungarian notation in naming conventions. There is sometimes even debate over whether or not coding standards are needed in the first place. The continued shift to Microsoft’s .NET platform has re-ignited the debates, since this shift presents an opportunity for companies to re-think the way they do software development.

As the lead developer of the Standards Master family of products, I’ve spent the last several years exploring coding standards in detail, particularly as they pertain to development with Microsoft tools. In this article, I’ll take a look at why coding standards are useful, what they should (and should not) contain, and how to enforce them. Although I’ll offer some advice along the way, my intention is not to decree “answers”. Rather, my goal is to provoke thought, whether your organization has a long, rigorous history of coding standards, is just now beginning the efforts, or hasn’t yet recognized their value. I’ll also describe how automated code reviews with Standards Master can help take the headache out of your code reviews, making reviews a constant, painless part of your development process.

The Case for Standards

When they are properly defined, trained, and enforced, coding standards can significantly reduce the cost of software development for organizations with many developers. So at the very least, there is a purely economic rationale to justify them: standards can make code easier to maintain, and can improve the readability of code across all projects in an organization, both of which make development cheaper.

Coding standards also help to homogenize code. Subtle (and not-so-subtle) inconsistencies can creep into source code written by many authors. Though they may not say it outright, many developers dislike working on code written by other developers because they inevitably find examples of code they would have written differently. Developers are creative by nature, and like artists, each brings his own style to the medium (i.e., the code). It is therefore natural for coding styles to diverge, even within the same source file – each developer who works on the file leaves his mark. Homogenization of source code through coding standards helps reduce the emphatic ownership some developers have on “their” code and the dislike for the code of others. When working with code written to an accepted standard, developers feel right at home, rather than being tempted to re-work all the code they touch to more fully align it with their personal tastes. Simply put, the standards facilitate the concept of source code as public asset, not a personal one. This, too, ultimately has a positive impact on the cost of development.

The consistency provided by standards yields less tangible, though perhaps no less important, benefits as well. For example, code that follows standards typically has fewer bugs, and the bugs that do exist are easier to find and fix. So in effect, having standards can help improve the quality of the code. Does this mean that code written up to a coding standard is bug-free? Of course not, but the consistency can make bugs easier to spot along the way – developers are more likely to find the bugs themselves while they are coding. And the sooner a bug is found, the cheaper it is to fix.

While I still run across a few individuals and organizations that think coding standards are a waste of time, in my experience, the overwhelming consensus is that they are indeed valuable. The real debate then is over what they should contain and how they should be adopted. The trick is to determine to what degree coding standards should be part of a company’s culture and how the managers and developers should realize this cultural shift.

Resistance to Coding Standards

So if most organizations agree that coding standards are helpful, why is it that not every company has them? There are a lot of reasons, but most boil down to time and money. It is time consuming and costly to get started with the effort of creating coding standards. Furthermore, maintenance and enforcement of the standards adds time and cost to what are usually already constrained budgets.

For companies whose development is project-based, some project usually has to eat the cost of creating the standards. This means that even if there is strong grass-root support for developing coding standards, organizations may forego the effort in favor of meeting tight schedules and budgets. However, ultimately, the argument that “we don’t have time to have coding standards on this project” is self-defeating, since companies eventually discover that they don’t have time not to.

There is also some potential for personality conflicts to hinder efforts to adopt coding standards. For example, programming is more art than science: just like some artists don’t like to be told how to create their art, some developers don’t like to be told how to code. Developers may, therefore, resent some aspects of coding standards, feeling they are too restrictive. This artistic side of programming may be at direct odds with the practical aspects of writing code for profit. For many developers, it’s the process of creating the code that is most satisfying to them, not necessarily the finished product, so things that may interfere with the process of creation (like standards) are viewed as a hindrance. The companies they work for are likely to have the opposite view – the finished product is the primary goal – the developers’ personal enjoyment in creating it is of secondary importance. Even when developers are not overly concerned with development as art, they are still creatures of habit, and changing these habits can be difficult.

Standards and Best Practices

The key to minimizing the perceived restrictiveness of coding standards without reducing their effectiveness is to develop standards that allow artistic freedom while still providing consistency. While I always encourage completely open discussions around coding standards when creating them, it is often helpful to frame the discussions by focusing on categorizing each of your topics as a standard or a best practice. There’s a fine line between the two, and it is critical for an organization actively creating coding standards to find this line. This is not to say you won’t still have disagreements, but it does provide a convenient high-level grouping.

I find it helpful to think of a standard as something that is cut-and-dried. Standards should have very few, if any, exceptions. Once they are defined, they should be followed without discussion. On the other hand, best practices are things that fall into the category of “this is generally the best way to handle this kind of situation, but there are cases when you’ll want to do it differently.” When context and developer discretion are required to determine how to handle a situation, you can define best practices, but it’s much more difficult to define a standard. Moreover, during reviews, you’ll want there to be discussion over situations where a best practice is not followed, but will find arguing over a standard violation (like a missing comment) to be a waste of everyone’s time.

By dividing aspects of coding into standards or best practices as appropriate, you’ll get a good start on your overall coding standards. Be sure to put these into a document and share it with your team.

What’s in a Standard?

FlexiSoft Solutions has been actively involved in helping people create and enforce coding standards for many years now. During this time, we’ve reviewed coding standards documents from dozens of companies, and have heard numerous testimonials from our customers about what works for them and what doesn’t. We’ve built much of this feedback and experience into our family of standards enforcement tools, Standards Master. Each version of Standards Master provides a great deal of flexibility in defining your coding standards, reflecting the tremendous variety we have found in our customers’ standards. Here’s a list of topics that you should at least consider putting into your standards document, along with some notes on what to expect as you explore them with your teams:

  • Commenting Style – In this area, you should address when developers should use header comments, what the required comment elements are, copyright information, etc. There are usually two schools of thought here: comment everything, or only comment what is needed. The topic of XML-style comments versus traditional flowerbox comments, and the topic of capturing revision history notes, usually draw some discussion as well.

    Standards Master provides full commenting capabilities, and supports any number of user-defined templates for your comments (XML-style or plain text). You can also define replaceable parameters for Standards Master to use to prompt the developer for additional information when adding a comment.

  • Formatting Style – The Visual Studio .NET IDE handles formatting for you (especially in Visual Basic .NET), but formatting style is still worth discussing, particularly if some of your developers use non-standard editors. Be sure to cover indentation conventions, spacing conventions, maximum line length, and bracketing conventions. This seems like a small topic, yet I know developers who waste a lot of time reformatting each others’ code. The benefits of standardization in cases like this are clear.

    Standards Master allows you to define any construct in your code as something which begins or ends an indentation level, plus fixes all spacing issues.

  • Naming Conventions – Naming conventions cover how classes, files, variables, namespaces, and everything else in your code should be named. This discussion could get ugly, though lately it seems developers are mostly concerned with how closely to follow Microsoft’s .NET naming convention guidelines. When working through this discussion, remember that Microsoft’s .NET conventions don’t apply to local and private member variables, so adopting their conventions without modification or enhancement will leave holes in your standards. And although Microsoft has actively tried to convince people not to use Hungarian notation (Pascal-case base names with scope, type, or other modifiers), they have not completely abandoned it themselves in their own guidelines, leaving their standards a bit inconsistent. I’ve found that most companies are augmenting Microsoft’s guidelines with bits of Hungarian notation to make things clearer. This is true in both Visual Basic .NET and C#. For example, scope prefixes (like _m, or m_ for class-level variables) and type prefixes (like s for String) are very common, though the Microsoft conventions don’t mention them. The good part is that you can usually define whatever you want for private constructs and still be consistent with Microsoft’s recommendations.

    Standards Master’s naming convention enforcement is very robust – it not only finds identifiers that do not follow your settings, but can fix them automatically for you. The AutoCorrect feature will actually fix naming convention problems as you type!

  • Code Construction – This broad category covers everything from obsolete language constructs to stylistic concerns. I recommend adopting practices that keep the code simpler (especially conditional, looping, and flow control constructs) and more readable. You may also want to consider defining threshold settings for things like the number of classes per file, lines per method, methods per class, characters per identifier, etc. A discussion of the acceptable use of GoTo statements is likely to be lively as well.

    Standards Master has dozens of code construction checks that may be configured any way you like. It can fix many code construction violations automatically for you as well.

  • Language-Specific Standards – Remember that coding standards usually are related to a specific language. Be sure to adopt standards for all languages your organization uses.

    Standards Master 2.0 supports Visual Basic 5 and 6. Standards Master 2004 and Standards Master 2005 support Visual Basic .NET, C#, and J#. All language-specific settings may be changed independently.

What to Do When You Agree To Disagree

Every effort to establish and maintain coding standards has its fair share of disagreement amongst the participants. I’m frequently asked how to handle situations in which the interested parties simply cannot agree on coding standards or are resisting efforts to define them. If you are spearheading the effort, there are a few things to keep in mind:

From the start, work with the developers who must abide by your standards while creating them. Developers will be much more likely to accept standards if they feel they have played an active role in their creation.

Be sure the standards you are creating are aligned with the corporate culture as much as possible. Don’t try to change everything overnight: sometimes a slow, steady adoption of coding standards is easier to sell.

When you can’t agree, learn to pick your battles. Determine which of the standards are really important and which aren’t. It is not worth losing sleep over missing standards that are not important. Allow your developers’ creative sides to emerge – don’t be too restrictive. Compromising on a few relatively unimportant standards may pave the way to enforce more important ones.

If there is still disagreement and no compromise is possible, find out if the dissenting opinions are really caused by displaced resentment for being told how to code or some unexplained fear of code reviews. If your organization is serious about having and enforcing coding standards, these developers will need to get over it.

When all else fails, a management mandate may be necessary to resolve a particular issue. This is best used as a last resort, but can help in extreme situations. I’ve seen cases where developers have quit or have been fired due to their unwillingness to follow (or even agree to) standards.

Be sure you have a mechanism in place to handle modifications to the standards once they are established. In my experience, a standards committee is usually a good idea, since it allows developers to continue to have an active role in the standards process.

Enforcing Standards through Code Reviews

Once you have established your coding standards, you should document them and train your developers. This is a critical first step in compliance. However, you’ll also need to set up some kind of review process to ensure the standards are followed. A lot of organizations take it on good faith that their developers will follow the standards and don’t bother setting up a review policy. In my experience, this is a mistake: personnel changes and tight schedules typically lead to cut corners if standards are not enforced consistently. If you don’t have a code review policy, you may not want to bother with coding standards at all.

In addition to helping ensure that developers follow your standards, code reviews are an excellent vehicle for communicating and disseminating corporate culture (also called “the-way-we-do-things-around-here”). Capitalize on this to help with training and polishing the skills of junior developers.

Code reviews are not without their drawbacks, though. When done poorly, they can be a drain on time and resources. And while the intention is to improve code through active, constructive criticism, developers are people, too. Some people do not accept (or give) criticism well. These problems are usually avoidable by having a clearly defined and trained standard in place, and focusing on techniques that remove egos and personalities from the reviews (as we’ll see below, automated reviews are excellent at this). Most importantly, emphasize that a code review is a code review, not a coder review. Still, code reviews can cause quite a bit of consternation to junior developers and others who like to hide in the complexity of their code.

Code Review Techniques

There are two techniques you can use to handle reviews, face-to-face reviews and automated reviews. These work best when used in combination, but both have their individual strengths as well. Let’s look at each in turn.

Face-to-face reviews may be used to verify that developers are following your standards, but are best when used to focus on logic and complexity in the code rather than the more rote aspects of coding. They are a great way to review how well best practices are being followed. Face-to-face reviews generally fall into three categories. First, peer reviews, in which one developer reviews the code of another, are great because they are convenient, though they can yield reviews of inconsistent quality. Second, group reviews, where some code is presented to a group of people for review (often the whole team), are also effective, since there is a lot of input. They can be time-consuming to execute, however. Third, senior developer reviews, where one or two senior programmers reviewing the code of the team, provide consistent, experienced feedback. Of course, you are left with the problem of determining who reviews the code of the senior developers. You can choose any of these three approaches in combination to handle your face-to-face reviews.

Automated reviews using Standards Master are very effective, since they can happen constantly, allowing violations to be addressed early in the coding process before they become entrenched in the code. Since Standards Master operates directly against source code rather than through metadata in compiled assemblies, it checks all of the code you choose (including local variables). The process is iterative: write some code, activate Standards Master through its toolbar to review the code, fix any problems found, and repeat. This means, developers review their own code while they work, fixing problems as they go. To make things even simpler, Standards Master can fix many of the problems it finds automatically. Ultimately, this means that code is written up to standard rather than brought up to standard.

Such automated reviews remove egos and personalities from the review process, making it much more palatable to a wider group of developers. Furthermore, automated reviews help developers not just in learning your standards, but to learn them at their own pace, without the potential embarrassment of having to be told something very simple is wrong by another developer. You can further automate the review process by using Standards Master’s command line interface to check code as part of your build scripts.

Standards Master is a very affordable, convenient tool for helping organizations enforce their coding standards. Used alone, it takes a good deal of the headache out of standards enforcement. However, it is best when used in conjunction with periodic peer and group reviews to yield the best quality for the smallest time commitment. With this combination, reviewers can spend more time focusing on the content and logic of the code, since the automated reviews with Standards Master remove the need to check the “mechanical” aspects of the standards, like comments, naming conventions, and code construction.

Conclusion

In the end, coding standards can significantly reduce the cost of the software you develop while simultaneously raising its quality. Code reviews provide an excellent way to enforce standards, instill corporate culture, and facilitate cross-training. While the initial adoption and ongoing enforcement of coding standards can seem daunting, the rewards are well worth the effort.

Copyright (c) 2006 FlexiSoft Solutions, Inc.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Dan Petit
Web Developer
United States United States
Dan Petit is President of FlexiSoft Solutions, Inc., which was founded in 1997 with the mission of creating quality tools for developers at a reasonable price. Since its inception, FlexiSoft Solutions has added both specialized training and consulting services to it offerings. Their offices are in Collierville, TN.
 
Dan is the author of the book Real Visual Basic and of numerous technical articles on object-oriented analysis and design, hardcore VB programming, UML modeling, and project management.

Comments and Discussions

 
GeneralVery nice article PinmemberBlitter23-Jan-07 5:38 
GeneralI'd love to have a commenting style... PinprotectorMarc Clifton21-May-06 14:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 2 May 2006
Article Copyright 2006 by Dan Petit
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid