"DaKoadMunky" <da*********@aol.com> wrote...
Say I have the following...
class Foo
{
public:
Foo() : bar(0) {}
void SetBar(int);
private:
int bar;
};
Say that an invariant for my class is that Foo::bar always be an even
number.
If somebody calls Foo::SetBar(int) with an odd number what is the best way
to
handle it?
1) assertions while in debug mode (if release mode let caller suffer the
consequences)?
2) throw an exception?
3) return an error code?
4) other?
In all cases I would leave the value of Foo::bar unchanged. The question
is
how and if to let the caller know the value was not changed.
Throwing an exception seems like the least likely solution. Is it valid
to use
exceptions to invalidate input or is that an abuse of exception handling?
I am leaning towards solution #1.
First, let me note that this is not a language problem. This is a software
engineering problem, or perhaps a library design problem. In any case, do
what you feel is the requirement of the users of the function.
Second, since you asked, I'll say where I lean. If you allow the user to
pass in _any_ value (as implied by the type and the name), throwing is not
the right thing, since no value is an _exception_. Debug-time assertions
are only good if you make sure your test runs cover _all_ cases, so you
only use assertions to find an error in the code that calls your function.
If you release your function to the user, assertions will not help. Error
codes are good if your user is going to actually verify them.
So, considering all that, none of your 1-4 suggestions would work. What to
do, you might ask. There is no fool-proof solution here, unfortunately.
I would probably implement the function as
void SetBarToEvenPartOf(int i) { bar = (i/2)*2; }
and document the hell out of the fact that calling that function with 3 will
actually set bar to 2.
V