Re: if Construction fails
Seungbeom Kim wrote:
kanze wrote:
It's not a panacea either, but generally, if the reasons for
failure depend on the arguments passed to the constructor, I
prefer to validate them before hand. The validation function
can use a return value, and if validation is a pre-condition to
the constructor, it can abort if the values are incorrect.
Doesn't it mean that the arguments should be checked
twice--once in the pre-construction validation, and once
during the construction?
In general, yes. If the profiler shows that this is a problem,
of course, the check in the constructor is an assert, which can
be compiled out.
If the constructor has to check the arguments to establish the
invariant anyway, what's the point of requiring another check
before construction?
Several reasons. The first, of course, is that the caller might
have some other way of knowing that the argments are OK, and can
avoid the check (with no logic in his code to handle it). The
second is it makes explicit what is being checked, and why, and
allows putting the error handling code immediately next to the
error detection code. Control flow is more easily verified.
In other words,
if (Foo::valid_args(args)) {
Foo foo(args);
// use foo
}
else {
// deal with invalid args
}
how is the code above better than the one below?
try {
Foo foo(args);
// use foo
}
catch (Foo::invalid_argument&) {
// deal with invalid args
}
It makes is clearer what you're testing for. But the first is
generally not what you'd write. More often, you'd write
something like:
if ( ! Foo::valid_args( args ) ) {
// very short error handling...
} else {
Foo foo( args ) ;
// significantly longer use of foo...
}
The form with try/catch suffers from two readability problems:
it's not immediately clear at the top what errors you're
handling locally; you have to scan down to the catch clause to
find out (and even that doesn't really tell you where they might
occur), and it forces you to put the error free path
first---some people prefer to put systematically put the shorter
path first, and some people prefer to handle all of the error
cases first.
(Yes, avoiding exceptions that are expected can save some
time, but checking the arguments twice for most of the valid
cases can also be time-consuming.)
Typically, the exception will be considerably more expensive
than the double check. When there is an error, of course. But
that has nothing to do with the motivation, which is entirely
based on readability.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]