Clean Code

A couple of simple rules that can help ensure code clarity, maintainability, performance, and stability:

  • Avoid using exceptions for flow controlThis is a seemingly obvious hint, yet many applications are tossing tens or hundreds of thousands of exceptions a second. While exceptions are a legitimate part of the flow control of the platform and language, contrary to the claims of the language-pruning self-annoited purists, they should be an exceptional flow control mechanism, not an alternative to a simple if condition.

    There are some performancecosts to exceptions, but more importantly they obfuscate the code flow, wrapping multiple scenarios that should be handled separately into one master grab-all. The most evil incarnation of exception usage is the lazy catch(Exception) { (or just catch {), an artifact that should be banished from your code (while it’s a benefit that .NET doesn’t required checked exceptions, it would have been nice if Microsoft more clearly documented the exceptions that methods in the .NET
    framework raise. It’s this lack of clarity that leads developers to use all encompassing exception handlers).

    Debug your applications with first-chance exceptions turned on (Debug/Exceptions, and set Common Language Runtime Exceptions to Break into the debugger). If you find that you’re constantly hitting continue, to the point that it’s irritating, then you’re probably relying too heavily on exceptions. Some exceptions do happen as a matter of course, and you can filter those out individually in the Debug/Exceptions panel.

  • Strive towards zero compiler warnings (set your compiler to treat warnings as errors) This is especially critical in teams: As developers hash out ideas, they’re often prone to sticking incomplete code in the codebase. Soon enough you have oodles and oodles of poorly thought out, poorly implemented warts throughout your application (for instance loads of unused variables), generating dozens or hundreds of warning messages. The problem with accepting this, and it’s similar to abusing exceptions, is that within all of the noise real problems will get lost.

    Warnings can serve as extremely valuable warning sign of coding problems, so make sure they can communicate these issues to you clearly.