Software programmers often use coding patterns to catch software defects. This usually entails encapsulating commonly used software pattern in wrapper classes or functions to ensure that the software pattern is used correctly.


Patterns don't eliminate the defects, but they assist in catching them. These types of patterns often make their way into language features. They may be as simple as const-correctness or as revolutionary as object-orientation. Other times they can be constructed from existing language features, such with templates in the case of shared_ptr / weak_ptr. Some start out as templates, such as static_cast, and turn into language features later. Another good example is the use of a statechart library (such as the one from Boost) rather than hand-rolling a state machines using switch statements.


Wrapper classes are often useful when performing code reviews in that certain types of code may discouraged by some teams in favor of using a class that will minimize or eliminate the chance of a particular type of error. For instance, "Never return a raw pointer from a function that requires the client to delete. Instead, return it as an auto_ptr, or mark the return value with dont_ignore"

Role in Static Code AnalysisEdit

As static code analysis tools become more sophisticated, desired coding patterns may be enforced using custom rules created for the tool. For instance, given the above example ("Never returning a raw pointer..."), rather than enforcing the use of auto_ptr or dont_ignore, one can simply allow for that kind of code to exist, but then use sophisticated execution path analysis features of the tool to catch scenarios where the caller does not correctly delete the returned pointer.

When Static Code Analysis isn't enoughEdit

Static code analysis tools can only do so much. In the above example, static execution path analysis may need to go quite deep to determine all of the places that pointers could have been stored by the client. There's a good argument to be made that if a coding pattern can be encapsulated in a wrapper class or function in an unobtrusive way, especially with regard to data size and performance, then the encapsulation of the pattern in a wrapper class should be preferred over a custom static code analysis rule to catch infractions from the raw code.

Community content is available under CC-BY-SA unless otherwise noted.