qazmlp said:
I have an 'if else' statement block like this:
if( inputArg != VALID_VALUE )
{
return error ;
}
else
{
// Do some major operation
return success ;
}
I am thinking of changing it to something like this:
if( inputArg != VALID_VALUE )
{
return error ;
}
// Do some major operation
return success ;
Which style do you recommend? Why?
When I'm checking for something I expect to happen in the normal course
of the program, my preference is to maintain a single point of exit:
Status function( Input const& input ) {
Status status; // To be returned.
if( ! valid( input ) ) {
status = error;
}
else { // Input is valid.
status = success;
}
return status;
}
The biggest reason for this is that it guarantees a place in each
function where I can check the function's value (and any other program
state) immediately before the function returns. This isn't something I
did in school; it took a couple of years of "real world" debugging to
appreciate.
If a run-time check uncovers a truly exceptional condition, I prefer to
throw an exception. "Truly exceptional" means (to me) that it may not
be feasible to recover from the error. If one of my functions is called
incorrectly, I typically throw, since I no longer trust the immediately
higher layer of the program.
template< typename N >
N reciprocal( N const& n ) {
if( n == 0 ) {
throw Exceptions:
ivision_by_zero(
"attempt to find reciprocal of zero" );
}
N result = 1/n;
return result;
}
In most of these cases I actually use an ASSERT macro to do the "throw
if check fails." I know Bjarne recommends using a template for
Assertions, but I like my error messages to include the failed
expression, as well as the file name and line number.
As Thore said, this is a pretty religious issue. Bright people have
suprisingly different philosophies. The conversation seems to be along
these lines:
A: I like to keep a single point of exit.
B: That makes the code less readable.
A: But much more debuggable.
B: No, you're wrong.
A: No, YOU are wrong.
B: Taste my wrath!
[ Mild flames ensue. ]
Whatever you do, you're likely to upset a few folks. Pick whatever
makes sense to you and go with it. If you change your mind later, at
least you'll know *why* the way you've been doing it is wrong. Then you
can be religious about it, too.