| Exploring Solution Spaces © Copyright 2003-2006, by C. Keith Ray | ||||||||||||||||||||||||
|
Archives
Subscribe |
2007.Oct.05 Fri "splogs" is inspired to use 'const' more in C++ after exposure to Haskell. Quote:
An anonymous commenter responded:
Consider this bit of code:
Results aFunction(SomeClass& anObject)
{
someval = anObject.SomeMethod();
// later...
someotherval = anObject.SomeOtherMethod();
// etc.
return results;
}
Given that anObject is not const, you'd have to assume that SomeMethod and SomeOtherMethod could be modifying the state of the object. If you changed the order of calls, or called one of those methods more than once, you could break the desired behavior. The only way to know for sure would be to look at the source-code and/or documentation for SomeClass's methods. Now with const-ness:
Results aFunction(const SomeClass& anObject)
{
someval = anObject.SomeMethod();
// later...
someotherval = anObject.SomeOtherMethod();
// etc.
return results;
}
The simple act of declaring anObject to be const also implies that SomeMethod and SomeOtherMethod are const methods. (The compiler will complain if that's not true). This assumes the programmer for SomeClass was following the rules (that is, he's not 'faking' const-ness) and SomeClass isn't modifying some external state that we care about. In this case with a const reference and const methods, we could be pretty sure that we could change the order of method calls, and the number of times the methods are called, with no effect on the correct behavior. Unfortunately, even with 'const' we can't always be sure the behavior is correct, so writing micro-tests helps enforce the intended behavior. A test like...
TEST(aFunctionDoesWhatWeWant)
{
SomeClass anObject; // set up how we want
Results fResults = aFunction(anObject);
AssertEqual(expectedState, anObject.GetState());
AssertEqual(expectedResults, fResults);
}
... would help us verify that the following changes are okay, if it still passes after changing the order and number of calls.
Results aFunction(const SomeClass& anObject)
{
someval = anObject.SomeMethod();
someotherval = anObject.SomeOtherMethod();
// later...
someotherval2 = anObject.SomeOtherMethod();
someval2 = anObject.SomeMethod();
// etc.
return results;
}
Declaring a function parameter const also helps tell other programmers that the function isn't going to try to change the object's value. Tests will help document the function's desired behavior. |
|||||||||||||||||||||||