Re: Particular Example about why should we not use GOTO
Jim Langston wrote:
"Alexander Block" <ablock84@googlemail.com> wrote in message
news:1175170788.391227.97830@o5g2000hsb.googlegroups.com...
On 29 Mrz., 09:54, "SoftEast" <hemendra.sw...@gmail.com> wrote:
Hi Buddies,
I have read a lot of stuffs regarding not using GOTO statements to
opt a good programming style
[Refhttp://david.tribble.com/text/goto.html]. Can anybody give a
particular lines of code which shows harmfullness of GOTO.
SoftEast...
I use it in Mobile Development for error handling and clean up.
Normally I would use
exceptions for that, but this would be to much overhead for mobile
phones. Here is an example:
bool DoSomething() //returns false on failure
{
SomeObject* obj1 = NULL, obj2 = NULL;
obj2 = new SomeObject();
if(!ThisMayFail(obj1))
goto failed;
obj2 = new SomeObject();
if(!ThisMayFail(obj2))
goto failed;
return true;
failed:
if(obj1 != NULL)
delete obj1;
if(obj2 != NULL)
delete obj2;
return false;
}
I think this kind of clean up technique is easy to understand and
maintain.
bool DoSomething() //returns false on failure
{
SomeObject* obj1 = NULL, obj2 = NULL;
try
{
obj2 = new SomeObject();
if(!ThisMayFail(obj1))
throw;
'throw' without a value is only useful inside a 'catch' clause.
It re-throws the exception caught. You should probably write
'throw 42' here.
obj2 = new SomeObject();
if(!ThisMayFail(obj2))
throw;
Same here.
return true;
}
catch(...)
{
if(obj1 != NULL)
delete obj1;
if(obj2 != NULL)
delete obj2;
There is no need to check for NULL before using 'delete'. Drop
those and you will have an even cleaner function.
return false;
}
}
Undserstanding that this code isn't deleting obj1 and obj2 on
success, just as the original code wasn't.
There are always alternatives to useing goto.
Of course, you may have intended success to fall through to the
cleanup, but it didn't because you were returning before you got
there. Which is the problem with goto's, it obfuscates code.
Exceptions are no better when obfuscation is concerned. With 'goto'
I can at least expect that the label is in the same function. With
exception handling, the thrown exception can be in a different
module altogether.
You're correct, there are alternatives. Not all of them are
available in any environment. Some embedded programs (I heard)
cannot contain exception handling.
Now, if I use 'auto_ptr', I can rewrite the 'DoSomething' as
bool DoSomething() //returns false on failure
{
auto_ptr<SomeObject> obj1(new SomeObject());
if(!ThisMayFail(obj1))
return false; // deletes obj1
auto_ptr<SomeObject> obj2(new SomeObject());
if(!ThisMayFail(obj2))
return false; // deletes obj2 _and_ obj1
obj1.release(); // obj1 forgets about the object it held
obj2.release(); // obj2 forgets about the object it held
return true; // deletes nothing
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask