Write const-correct code. Methods which do not modify the state of the object (i.e. do not change the value of any data member), are to be declared const. This enables the reader to know immediately that calling such a method does not change the state of the object it is being operated on. In some cases, such as cache management, internal data is not modified by an otherwise const method. In such case, rather than remove the constness from the method, instead mark the data member as mutable. This is okay to do because the state of the object really isn’t changing – the cached data is redundant.

This page is an example of Catching defects with Patterns.

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