Thursday, October 4, 2007

Treat warnings as errors

Compiler warnings can provide some additional insight and quality controls on your codebase.  They can tell you about obsolete code, unused variables, and many other items that you wouldn't necessarily see on visual inspection.  Warnings can also surface bugs, such as possible null reference exceptions, or expressions that always evaluate to "true".

However, compiler warnings can be easily ignored.  Ignore them for long enough, and important warnings can be lost in a sea of "acceptable" warnings.  For higher quality code, you can treat warnings as errors.  When a compile time warning is found, the compilation fails.  Warnings also have varying severity, from "0" (basically off) to "4", which includes all warnings.  Set your warning levels to "4" to get the most mileage.

To turn on "Treat warnings as errors", go to the property pages for your a project and click the "Build" section.  In the section "Treat warnings as errors", set it to "All" and set the warning level to "4":

If you use the aspnet_compiler tool or Web Deployment Projects, you can also turn on "Treat warnings as errors" for these pre-compilation steps in the web.config file (.NET 2.0 in this example):

  <system.codedom>

    <compilers>

      <compiler

        language="c#;cs;csharp"

        extension=".cs"

        type="Microsoft.CSharp.CSharpCodeProvider, System,

          Version=2.0.3600.0, Culture=neutral,

          PublicKeyToken=b77a5c561934e089"

        compilerOptions="/warnaserror"

        warningLevel="4"

      />

    </compilers>

  </system.codedom>

The compilers section allows me to fine tune my ASP.NET compilation options, including warning levels and treating warnings as errors.

By treating warnings as errors, I can start dialing up the quality of our code a little at a time, producing a more maintainable codebase.

No comments: