Re: Only one point of return
* werasm:
Alf P. Steinbach wrote:
but if so, try
bool f()
{
if( pointer1 != 0 )
{
pointer1->doSomething();
if( pointer1 != 0 )
{
pointer2->doSomething1();
return true;
}
}
return false;
}
Hmmm, or:
bool f()
{
if( pointer1 == 0 ){ return false; }
pointer1->doSomething();
if( pointer2 == 0 ){ return false; }
pointer2->doSomething();
return true;
}
I like this because it seems less complex to read and understand, but
the rationale is of course subjective (as is SESE and SEME in C++,
depending to who you speak).
Both versions are SEME. Yours is less clear because you can't tell at a
glance under which conditions it will return true. You have to
laboriously analyse the complete code in order to establish that.
I like getting the pre-conditions out of
the way before handling the meat.
That's always necessary for precondition checking. Here we have no
function level preconditions. But if we had, then checking them after
they apply would not be a matter of like or dislike, it would simply be
incorrect with possible undefined behavior.
SEME for me seems to do this better than SESE.
Often yes. Both versions above are SEME.
Another alternative...
template <class T>
class ExistentPtr
{
public:
ExistentPtr
( T*& p );
T& operator*() const; //throws if pointer_ NULL.
T* operator->() const; //throws if pointer_ NULL.
private:
T*& pointer_;
};
bool f()
{
ExistentPtr<Type> p1( pointer1 );
ExistentPtr<Type> p2( pointer2 );
try
{
p1->doSomething();
p2->doSomething();
return true;
}
catch( const null_ptr_error& )
{
return false;//
}
}
Is both needlessly inefficient and unclear. Are the conditions under
which p2->doSomething() is executed, intentional or an arbitrary side
effect of using ExistenPtr? Impossible to tell, and that's a nightmare
for the one maintaining the code, who must then check all /calling/ code
for expectations about f's behavior (or lack of behavior).
Perhaps, if a function is written properly, it may never require
visible ifs
for the sake of handling errors, but this is very subjective.
What makes you think the original example was handling any errors? It
looked like normal case code to me. For errors, terminate or throw.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?