473,383 Members | 1,846 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

if clause

Hello,

i have a question about "design" issues in C.

In ACMqueue of february
(article here:
http://www.acmqueue.org/modules.php?...owpage&pid=364
), KV says:
A dangerous if clause is one in which the code you want to protect
with the if isn't really protected. Consider the following pseudocode:

0: if (out < 0)
1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)

(...)
The reason that all the if statements were added was to protect
the program from calling the write() function when there was
a problem, so the code should be structured in just that way:

0: if ((out >= 0) && (permission >= operator) && (data.len() 0))
1: write(out, data, data.len)
2: // Put all the error condition returns here.
In my mind, man can argue with the latter code, man has to copy the error
checks
and have twice the same code. What do you thinks about this code snippet?
Thanks for your replies,

rogz
Oct 30 '06 #1
27 5338
rogz wrote:
i have a question about "design" issues in C.

In ACMqueue of february
(article here:
http://www.acmqueue.org/modules.php?...owpage&pid=364
), KV says:
A dangerous if clause is one in which the code you want to protect
with the if isn't really protected. Consider the following pseudocode:

0: if (out < 0)
1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)

(...)
The reason that all the if statements were added was to protect
the program from calling the write() function when there was
a problem, so the code should be structured in just that way:

0: if ((out >= 0) && (permission >= operator) && (data.len() 0))
1: write(out, data, data.len)
2: // Put all the error condition returns here.
I fail to see how the original code was "dangerous". I tend not to
trust
a coder who thinks return expressions have to be parenthasised. I might
write the code in the form shown.
In my mind, man can argue with the latter code, man has to copy the error
checks
and have twice the same code. What do you thinks about this code snippet?
who is "man", is it a new age thing? I'd respond if I understood you.
--
Nick Keighley

Oct 30 '06 #2
>In my mind, man can argue with the latter code, man has to copy the error
checks
and have twice the same code. What do you thinks about this code snippet?

who is "man", is it a new age thing? I'd respond if I understood you.
Err.. You should read "one" instead of "man".

rogz
Oct 30 '06 #3
Nick Keighley wrote:
In my mind, man can argue with the latter code, man has to copy the error
checks
and have twice the same code. What do you thinks about this code snippet?

who is "man", is it a new age thing? I'd respond if I understood you.
It's German for "one", when used as a pronoun.

Regards,
Bart.

Oct 30 '06 #4

rogz wrote:
Hello,

i have a question about "design" issues in C.

In ACMqueue of february
(article here:
http://www.acmqueue.org/modules.php?...owpage&pid=364
), KV says:
A dangerous if clause is one in which the code you want to protect
with the if isn't really protected. Consider the following pseudocode:

0: if (out < 0)
1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)

(...)
The reason that all the if statements were added was to protect
the program from calling the write() function when there was
a problem, so the code should be structured in just that way:

0: if ((out >= 0) && (permission >= operator) && (data.len() 0))
1: write(out, data, data.len)
2: // Put all the error condition returns here.

In my mind, man can argue with the latter code, man has to copy the error
checks
and have twice the same code. What do you thinks about this code snippet?
Well, as I recently changed a piece of code from the second format to
the first (roughly) to make it clearer and more expressive (at least in
my opinion :-), I disagree with the transformation suggested.

Oct 30 '06 #5

"rogz" <ro******@gmail.comwrote in message
news:45**********@news.bluewin.ch...
Hello,

i have a question about "design" issues in C.

In ACMqueue of february
(article here:
http://www.acmqueue.org/modules.php?...owpage&pid=364
), KV says:
A dangerous if clause is one in which the code you want to protect
with the if isn't really protected. Consider the following pseudocode:

0: if (out < 0)
1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)

(...)
The reason that all the if statements were added was to protect
the program from calling the write() function when there was
a problem, so the code should be structured in just that way:

0: if ((out >= 0) && (permission >= operator) && (data.len() 0))
1: write(out, data, data.len)
2: // Put all the error condition returns here.

In my mind, man can argue with the latter code, man has to copy the error
checks
and have twice the same code. What do you thinks about this code snippet?
Thanks for your replies,

rogz

I took a few minutes to look at the other articles posted by this fellow on
acmQueue. I wouldn't put much stock in his offerings.
Oct 30 '06 #6

rogz wrote:
0: if (out < 0)
1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)

There are several disparate issues with this code and the original
writer wasnt very good at pointing them out. Here's my view:

(1) Some people think a function should have just ONE clear exit
point, at the bottom. I realize that can get a bit long-winded, but it
can make the code MUCH CLEARER, much easier to set breakpoits, much
easier to add code you're SURE will get run every time. Multiple entry
points went out with FORTRAN II, why do we still have multiple exit
points in this 21sh century?

Now to get just one exit point TAKES A LITTLE MORE WORK and a little
more nesting or use of "break". Personally I'm a nervous nelly and
won't use "break" (see ATT $400 million looss due to the vagaries of
"break"). So I end up with code like the stuff below. Your opinion
may vary. :

ErrorType Answer;
if( out >= 0 ) {
if( permission >= operator ) {
if( data.len 0 ) {
Answer = write( ....) 0;
} else Answer = BADLEN;
}
else Answer = BADPERMS;
} else Answer = BADOUT

return Answer;

--------------
Now I know in a large function with a lot of error checks the code can
get a bit indented.
It's a tradeoff. Personally I don't mind indenting if it makes the
code clean, flow-thruough, and with obvious entry and exit points.

Your opinion may vary.

------------------

(2) Second point, do you use positive or negative logic. Personally I
don't think it matters a whole lot whether you filter out the BAD
conditions or include in the GOOD conditions, as long as the conditions
make some kind of logical sense. The original code detected the BAD
conditions in a series of if's, saying in effect, if this or this or
this then return an error, the alternative being: if this and this and
this then do the work else various errors. I'd try to keep to one
paridigm or the other, mixing if this but not that can get confusing.

Your opinion may vary.

Oct 30 '06 #7
>>0: if (out < 0)
>>1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)
"Ancient_Hacker" <gr**@comcast.netwrites:
(1) Some people think a function should have just ONE clear exit
point, at the bottom. I realize that can get a bit long-winded, but it
can make the code MUCH CLEARER,
Or much less clear when it comes into nesting ifs which, IMO, is less
readable then returning when error condition occurs.
much easier to set breakpoits, much
easier to add code you're SURE will get run every time. Multiple entry
points went out with FORTRAN II, why do we still have multiple exit
points in this 21sh century?
I believe, I've heard about some research showing that programmers
tend to make less errors when they are allowed to use 'break' - maybe
the same goes to multiple exit points.
Now to get just one exit point TAKES A LITTLE MORE WORK and a little
more nesting or use of "break".
Isn't "break" really cheating? Like in:

#v+
answer;
do {
some stuff;
if (error 1) {
answer = error1;
break;
}
some stuff();
if (error 2) {
answer = error2;
break;
}
some stuff;
if (error 1) {
answer = error2;
break;
}
some stuff;
answer = success;
} while (0);
return answer;
#v-

It looks just like the same function with many exit points but
uglier.

Just showing my point of view though.

Personally I'm a nervous nelly and won't use "break" (see ATT $400
million looss due to the vagaries of "break"). So I end up with
code like the stuff below. Your opinion may vary. :

ErrorType Answer;
if( out >= 0 ) {
if( permission >= operator ) {
if( data.len 0 ) {
Answer = write( ....) 0;
} else Answer = BADLEN;
}
else Answer = BADPERMS;
} else Answer = BADOUT

return Answer;
Why not:

#v+
ErrorType Answer;
if (out<0) {
Answer = BADOUT
} else if (permission<operator) {
Answer = BADPERMS;
} else if (data.len<=0) {
Answer = BADLEN;
} else {
Answer = write(...) 0;
}
return Answer;
#v-
--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>---<jid:mina86*chrome.pl>--ooO--(_)--Ooo--
Oct 30 '06 #8
Ancient_Hacker said:

<snip>
Now I know in a large function with a lot of error checks the code can
get a bit indented.
It's a tradeoff. Personally I don't mind indenting if it makes the
code clean, flow-thruough, and with obvious entry and exit points.

Your opinion may vary.
My opinion varies, insofar as I would prefer to see a large function broken
up into smaller ones. As well as making the code simpler to understand (if
done properly!), this also has the advantage of reducing the indent level -
which, again, aids readability.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 30 '06 #9

Michal Nazarewicz wrote:
Why not:
ErrorType Answer;
if (out<0) {
Answer = BADOUT
} else if (permission<operator) {
Answer = BADPERMS;
} else if (data.len<=0) {
Answer = BADLEN;
} else {
Answer = write(...) 0;
}
return Answer;
Yep, that looks okay too, and in a sense clearer as the error condition
is right by the error code, instead of down at the end of all the
ifs().

Yet another way is to hide all the error checking and nesting in a
macro, something like:

(to just log the first error)
#define Ensure(cond,code) if( Answer == Okay ) if(!cond) Answer =
code; )

(to log all errors)
#define Ensure(cond,code) if(!cond) Answer |= code; )

Answer = Okay;
Ensure( out >= 0, BADOUT )
Ensure( permission operator, BADPERMS )
Ensure( data.len 0, BADLEN )
if( Answer == Okay )
Answer = write(...);
return Answer;
I know, a few more nanoseconds of overhead, but the upside is you lose
all the nesting, curlies, and you're encouraged to write the checks in
a consistent way. Your opinion probably varies.

Oct 30 '06 #10
Ancient_Hacker wrote:
rogz wrote:
>>0: if (out < 0)
1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)


There are several disparate issues with this code and the original
writer wasnt very good at pointing them out. Here's my view:

(1) Some people think a function should have just ONE clear exit
point, at the bottom. I realize that can get a bit long-winded, but it
can make the code MUCH CLEARER, much easier to set breakpoits, much
easier to add code you're SURE will get run every time. Multiple entry
points went out with FORTRAN II, why do we still have multiple exit
points in this 21sh century?
This is certainly a common opinion, but the code I maintain embraced the
other approach: if you have special cases while setting up the main meat
of the function that suggest that continuing makes no sense, then bail
out early.

We have a whole runtime-enabled logger system so, as long as you log the
entry and exit, debugging is easy and the code is easy to read.

Once we get into the main logic for the function we usually have the
usual assortment of breaks to ensure that there is only one more exit
point to be had.

The other approach I've seen is to have all the special cases handled by
a number of "goto early" or "goto error", where the return is normalized
and control short-circuited to the exit point.

All of these approaches make sense under the right circumstances, but
this maintenance drone prefers code that can be easily read,
top-to-bottom, to figure out what it is *supposed* to do so the bugs are
easier to find.

Freeing up my cognitive energy by being able to discard early control
paths as I go really helps me solve some obscure problems. It also
allows one to say with accuracy that some variable or parameter is in
some known range (e.g., some value is or is not null, or some parameter
cannot possibly be 0, &etc.) after some specific point.

I'm speaking as someone who might not be able to run a debugger on live
code (I maintain chunks that are compiled with older compilers that have
crufty debuggers that don't run on later releases of Windows, for example).
Oct 30 '06 #11
On 30 Oct 2006 06:17:28 -0800, "Ancient_Hacker" <gr**@comcast.net>
wrote:
>(1) Some people think a function should have just ONE clear exit
point, at the bottom. I realize that can get a bit long-winded, but it
can make the code MUCH CLEARER, much easier to set breakpoits, much
easier to add code you're SURE will get run every time. Multiple entry
points went out with FORTRAN II, why do we still have multiple exit
points in this 21sh century?
Because in some circumstances, it makes the code much clearer, much
easier to set breakpoints, and much easier to add code to individual
tests.

IOW, "some people" are not always right. In the example given, I would
prefer the form presented as a bad example :-)

BTW, what do multiple entry points have to do with multiple exit
points?

--
Al Balmer
Sun City, AZ
Oct 30 '06 #12
Michal Nazarewicz wrote:
>>>0: if (out < 0)
1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)
Makes me feel uncomfortable
>
"Ancient_Hacker" <gr**@comcast.netwrites:
>(1) Some people think a function should have just ONE clear exit
point, at the bottom. I realize that can get a bit long-winded, but it
can make the code MUCH CLEARER,
I agree totally, especially when maintaining code that has grown to a
hundred lines per function.
>
Or much less clear when it comes into nesting ifs which, IMO, is less
readable then returning when error condition occurs.
which is why I prefer "exceptions first with else if" or goto error exit
>
>much easier to set breakpoits, much
easier to add code you're SURE will get run every time. Multiple entry
points went out with FORTRAN II, why do we still have multiple exit
points in this 21sh century?

I believe, I've heard about some research showing that programmers
tend to make less errors when they are allowed to use 'break' - maybe
the same goes to multiple exit points.
>Now to get just one exit point TAKES A LITTLE MORE WORK and a little
more nesting or use of "break".

Isn't "break" really cheating? Like in:

#v+
answer;
do {
some stuff;
if (error 1) {
answer = error1;
break;
}
some stuff();
if (error 2) {
answer = error2;
break;
}
some stuff;
if (error 1) {
answer = error2;
break;
}
some stuff;
answer = success;
} while (0);
return answer;
#v-
I would say yes, since it can easily be handled with a reasonable amount of
indenting (and if it can't then it's time to consider two smaller
functions)
>
It looks just like the same function with many exit points but
uglier.

Just showing my point of view though.

>Personally I'm a nervous nelly and won't use "break" (see ATT $400
million looss due to the vagaries of "break"). So I end up with
code like the stuff below. Your opinion may vary. :

ErrorType Answer;
if( out >= 0 ) {
if( permission >= operator ) {
if( data.len 0 ) {
Answer = write( ....) 0;
} else Answer = BADLEN;
}
else Answer = BADPERMS;
} else Answer = BADOUT

return Answer;
For that depth that would satisfy me
>
Why not:

#v+
ErrorType Answer;
if (out<0) {
Answer = BADOUT
} else if (permission<operator) {
Answer = BADPERMS;
} else if (data.len<=0) {
Answer = BADLEN;
} else {
Answer = write(...) 0;
}
return Answer;
#v-
although I prefer that
>
And then, of course, since I prefer data-oriented to process-oriented, there
is
Answer = out < 0 ? BADOUT :
permission < operator ? BADPERMS :
data.len() <= 0 ? BADLEN :
write(...) <= 0 ? BADWRITE :
SUCCESS;
--
Bill Medland
Oct 30 '06 #13
Ancient_Hacker wrote:
>
(1) Some people think a function should have just ONE clear exit
point, at the bottom. I realize that can get a bit long-winded, but it
can make the code MUCH CLEARER, much easier to set breakpoits, much
easier to add code you're SURE will get run every time. Multiple entry
points went out with FORTRAN II, why do we still have multiple exit
points in this 21sh century?
Because there's one reason to enter a function ("Do this
specified thing") but many reasons the function might not be
able to do its job ("Logarithm of negative number" or "File
not found" or "Inauspicious lunar phase").

Even the "not do its job" part is suspect: Some functions
can succeed in multiple different ways. "Item was present in
hash table" or "Item was not present but was inserted" or
"New file opened for output" or "Old file erased and truncated
to zero length, now ready for output."

Insisting that all modes of failure and all modes of success
must somehow filter down to one great holy return statement is
not good practice, but monotheism run rampant. "Thou shalt have
no RETURN before Me" -- pfui!

--
Eric Sosman
es*****@acm-dot-org.invalid
Oct 31 '06 #14
Eric Sosman said:

<snip>
>
Insisting that all modes of failure and all modes of success
must somehow filter down to one great holy return statement is
not good practice, but monotheism run rampant. "Thou shalt have
no RETURN before Me" -- pfui!
Pfui schmui. This isn't about religion, but about clarity. If we can write
the code in a way that a maintenance droid will be able to understand
easily in five years' time, then that's a Good Thing. Personally, I find
code easier to understand if it doesn't arbitrarily leap off a cliff under
certain conditions, at apparently random intervals.

The thing that put me off multiple returns was not success/failure -
bail-out code is easy to understand, and the only caveat is "was it a clean
failure?" (e.g. let's remember to clean up memory, close any files that
shouldn't be open if the operation failed, etc etc). Rather, it was when I
was having to modify long-winded financial calculations that had return
statements sprinkled liberally through the (oversized) function.
Unravelling the "let's squeeze the last nanosecond out of this mainframe"
code so that I could do the mod properly was an exercise in torture. And
one of the worst culprits was this "oh, look, we're in six levels of loop,
this seems a suitably arbitrary place, so let's return the value of this
badly named variable. Or perhaps we should wait until we get to the next
loop, where we can return the value of an *even more* badly named
variable!"

I wouldn't want to put anyone through that. So I don't.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 31 '06 #15
Richard Heathfield wrote:
Eric Sosman said:

<snip>
>>
Insisting that all modes of failure and all modes of success
must somehow filter down to one great holy return statement is
not good practice, but monotheism run rampant. "Thou shalt have
no RETURN before Me" -- pfui!

Pfui schmui. This isn't about religion, but about clarity. If we can write
the code in a way that a maintenance droid will be able to understand
easily in five years' time, then that's a Good Thing. Personally, I find
code easier to understand if it doesn't arbitrarily leap off a cliff under
certain conditions, at apparently random intervals.

The thing that put me off multiple returns was not success/failure -
bail-out code is easy to understand, and the only caveat is "was it a clean
failure?" (e.g. let's remember to clean up memory, close any files that
shouldn't be open if the operation failed, etc etc). Rather, it was when I
was having to modify long-winded financial calculations that had return
statements sprinkled liberally through the (oversized) function.
Unravelling the "let's squeeze the last nanosecond out of this mainframe"
code so that I could do the mod properly was an exercise in torture. And
one of the worst culprits was this "oh, look, we're in six levels of loop,
this seems a suitably arbitrary place, so let's return the value of this
badly named variable. Or perhaps we should wait until we get to the next
loop, where we can return the value of an *even more* badly named
variable!"

I wouldn't want to put anyone through that. So I don't.
Arguing that X is bad because you've seen bad examples of X isn't
very convincing, unless you can show that there are no /good/
examples of X.

The code you describe apparently fails the clarity test in at least
two other ways. (fx:assert) Code that /didn't/ fail those clarity
tests and used multiple returns can still be clear.

--
Chris "hashed up hashing" Dollin
"Who are you? What do you want?" /Babylon 5/

Oct 31 '06 #16
Chris Dollin said:
Richard Heathfield wrote:
<snip>
>>
The thing that put me off multiple returns was [...]

I wouldn't want to put anyone through that. So I don't.

Arguing that X is bad because you've seen bad examples of X isn't
very convincing, unless you can show that there are no /good/
examples of X.
I'm not trying to argue that X is bad. I'm just pointing out that in *my*
experience I find X hard to maintain in general terms, and consequently I
don't like to inflict X on other people (including myself). Clarity takes
precedence over religion.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 31 '06 #17
Richard Heathfield wrote:
Chris Dollin said:
>Richard Heathfield wrote:
<snip>
>>>
The thing that put me off multiple returns was [...]

I wouldn't want to put anyone through that. So I don't.

Arguing that X is bad because you've seen bad examples of X isn't
very convincing, unless you can show that there are no /good/
examples of X.

I'm not trying to argue that X is bad. I'm just pointing out that in *my*
experience I find X hard to maintain in general terms, and consequently I
don't like to inflict X on other people (including myself). Clarity takes
precedence over religion.
I think we agree on that last sentence. And, in practice, I suspect
our code might be more alike than disputes like this might suggest.

Is "Clarity takes precedence over religion." a religion?

--
Chris "(fx:quack) diagonal" Dollin
"We did not have time to find out everything we wanted to know."
- James Blish, /A Clash of Cymbals/

Oct 31 '06 #18
Chris Dollin said:
Richard Heathfield wrote:
<snip>
>Clarity takes precedence over religion.

I think we agree on that last sentence. And, in practice, I suspect
our code might be more alike than disputes like this might suggest.
I suspect you're right. All well-maintained roads lead to clarity.
Is "Clarity takes precedence over religion." a religion?
It's not clear.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 31 '06 #19
Ancient_Hacker wrote:
Multiple entry points went out with FORTRAN II, why do we still have
multiple exit points in this 21sh century?
One can use setjmp() and longjmp() to create multiple entry points.

Or is that different?
Oct 31 '06 #20
In article <11**********************@b28g2000cwb.googlegroups .com>,
Ancient_Hacker <gr**@comcast.netwrote:
>Multiple entry points went out with FORTRAN II
That's a useless analogy. It's like arguing against "goto" because
we (almost) all agree that "comefrom" is a bad idea.

-- Richard
Oct 31 '06 #21
On Tue, 31 Oct 2006 06:53:58 +0000, Richard Heathfield
<in*****@invalid.invalidwrote:
>Eric Sosman said:

<snip>
>>
Insisting that all modes of failure and all modes of success
must somehow filter down to one great holy return statement is
not good practice, but monotheism run rampant. "Thou shalt have
no RETURN before Me" -- pfui!

Pfui schmui. This isn't about religion, but about clarity. If we can write
the code in a way that a maintenance droid will be able to understand
easily in five years' time, then that's a Good Thing. Personally, I find
code easier to understand if it doesn't arbitrarily leap off a cliff under
certain conditions, at apparently random intervals.
There's no question that a function with multiple returns can be done
badly. So can a function with a single return. OTOH, "single return"
as a religion can also lead to impaired clarity and maintainability.
>
The thing that put me off multiple returns was not success/failure -
bail-out code is easy to understand, and the only caveat is "was it a clean
failure?" (e.g. let's remember to clean up memory, close any files that
shouldn't be open if the operation failed, etc etc). Rather, it was when I
was having to modify long-winded financial calculations that had return
statements sprinkled liberally through the (oversized) function.
Unravelling the "let's squeeze the last nanosecond out of this mainframe"
code so that I could do the mod properly was an exercise in torture. And
one of the worst culprits was this "oh, look, we're in six levels of loop,
this seems a suitably arbitrary place, so let's return the value of this
badly named variable. Or perhaps we should wait until we get to the next
loop, where we can return the value of an *even more* badly named
variable!"

I wouldn't want to put anyone through that. So I don't.
--
Al Balmer
Sun City, AZ
Oct 31 '06 #22
Spoon wrote:
Ancient_Hacker wrote:
>Multiple entry points went out with FORTRAN II, why do we still have
multiple exit points in this 21sh century?

One can use setjmp() and longjmp() to create multiple entry points.

Or is that different?
Yes. setjmp() and longjmp() were invented only to confuse and alarm us
maintenance drones. They actually have no other significant use.
Oct 31 '06 #23
Clever Monkey wrote:
Spoon wrote:
>Ancient_Hacker wrote:
>>Multiple entry points went out with FORTRAN II, why do we still have
multiple exit points in this 21sh century?

One can use setjmp() and longjmp() to create multiple entry points.
Or is that different?

Yes. setjmp() and longjmp() were invented only to confuse and alarm us
maintenance drones. They actually have no other significant use.
Hey! So it was you who wrote the Linux man page :-)

<quote>
setjmp() makes programs hard to understand and maintain.
If possible an alternative should be used.
</quote>
Nov 2 '06 #24
Ancient_Hacker wrote:
rogz wrote:
>>0: if (out < 0)
1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)


There are several disparate issues with this code and the original
writer wasnt very good at pointing them out. Here's my view:

(1) Some people think a function should have just ONE clear exit
point, at the bottom. I realize that can get a bit long-winded, but it
can make the code MUCH CLEARER, much easier to set breakpoits, much
easier to add code you're SURE will get run every time. Multiple entry
points went out with FORTRAN II, why do we still have multiple exit
points in this 21sh century?

Now to get just one exit point TAKES A LITTLE MORE WORK and a little
more nesting or use of "break". Personally I'm a nervous nelly and
won't use "break" (see ATT $400 million looss due to the vagaries of
"break"). So I end up with code like the stuff below. Your opinion
may vary. :

ErrorType Answer;
if( out >= 0 ) {
if( permission >= operator ) {
if( data.len 0 ) {
Answer = write( ....) 0;
} else Answer = BADLEN;
}
else Answer = BADPERMS;
} else Answer = BADOUT

return Answer;

--------------
Now I know in a large function with a lot of error checks the code can
get a bit indented.
It's a tradeoff. Personally I don't mind indenting if it makes the
code clean, flow-thruough, and with obvious entry and exit points.

Your opinion may vary.

------------------

(2) Second point, do you use positive or negative logic. Personally I
don't think it matters a whole lot whether you filter out the BAD
conditions or include in the GOOD conditions, as long as the conditions
make some kind of logical sense. The original code detected the BAD
conditions in a series of if's, saying in effect, if this or this or
this then return an error, the alternative being: if this and this and
this then do the work else various errors. I'd try to keep to one
paridigm or the other, mixing if this but not that can get confusing.

Your opinion may vary.
I'd go for the bad code as well, exiting if an error condition was found
because this way one could

1) set a break point on the bad return statement to see wheather it was
executed

2) with a small comment, the exit reason could be lovely described as in
"// we really need an open file here" and it could be logged better as
well, such as in cerr << "class::foo() need an open file\n" ; (don't get
started on correctness please) instead of "could not execute for one of
the 3 reasons: ..." and

3) in my company there's a standard in place telling me to not make
lines wider than 80 or so characters. if i always wanted to put all the
tests in one line - which couldn't be done - it would simply look like a
complete mess

m

Dec 23 '06 #25
Ancient_Hacker wrote:
rogz wrote:
>>0: if (out < 0)
1: return (fileError)
2:
3: if (permission < operator)
4: return (permissionError)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)


There are several disparate issues with this code and the original
writer wasnt very good at pointing them out. Here's my view:

(1) Some people think a function should have just ONE clear exit
point, at the bottom. I realize that can get a bit long-winded, but it
can make the code MUCH CLEARER, much easier to set breakpoits, much
easier to add code you're SURE will get run every time. Multiple entry
points went out with FORTRAN II, why do we still have multiple exit
points in this 21sh century?

Now to get just one exit point TAKES A LITTLE MORE WORK and a little
more nesting or use of "break". Personally I'm a nervous nelly and
won't use "break" (see ATT $400 million looss due to the vagaries of
"break"). So I end up with code like the stuff below. Your opinion
may vary. :

ErrorType Answer;
if( out >= 0 ) {
if( permission >= operator ) {
if( data.len 0 ) {
Answer = write( ....) 0;
} else Answer = BADLEN;
}
else Answer = BADPERMS;
} else Answer = BADOUT

return Answer;

--------------
Now I know in a large function with a lot of error checks the code can
get a bit indented.
It's a tradeoff. Personally I don't mind indenting if it makes the
code clean, flow-thruough, and with obvious entry and exit points.

Your opinion may vary.

------------------

(2) Second point, do you use positive or negative logic. Personally I
don't think it matters a whole lot whether you filter out the BAD
conditions or include in the GOOD conditions, as long as the conditions
make some kind of logical sense. The original code detected the BAD
conditions in a series of if's, saying in effect, if this or this or
this then return an error, the alternative being: if this and this and
this then do the work else various errors. I'd try to keep to one
paridigm or the other, mixing if this but not that can get confusing.

Your opinion may vary.
btw, i also find nested if/else statements quite unsuitable. consider

if( ... )
{
// ..
if( ... )
{
// ..
if( ... )
{
// ...
}
else
{
// ..
}
// ..
}
else
{
// ..
}
// ..
}
else
{
// ..
if( .. )
{
if( .. )
{
// ..
}
// ..
}
else
{
// ..
if( .. )
{
// ..
}
else
{
// ..
switch( ... ) // little fun here
{
case a: // code here
break ;
case b: // code here
break ;
case c: // code here
break ;
default: // code here
}
// ..
}
}
// ..
}

this is .. how's it called .. "well structured" indeed and I've
actually seen this.
the only thing is that it's so bloody hard to wrap your head around
what's going on and, honestly, I'd not let someone do this a 2nd time.

m
Dec 23 '06 #26

Clever Monkey wrote:
Yes. setjmp() and longjmp() were invented only to confuse and alarm us
maintenance drones. They actually have no other significant use.
Mr. Clever is probably joking, but I'd be interested to
see what comp.lang.c'ers would come up with if they
rewrote the program shown in
http://groups.google.com/group/rec.p...0f0e2a8cf4ed01
to avoid longjmp().

If you're allergic to clicking on groups.google links,
here is the essential part of the message above:
==logic/dell.s <==
#include <setjmp.h>

#define EITHER if (S[1] = S[0], ! setjmp((S++)->jb)) {
#define OR } else EITHER
#define REJECT longjmp((--S)->jb, 1)
#define END_EITHER } else REJECT;
....
EITHER /* Clue 5 */
yes(IVORY, HOUSE_0);
yes(GREEN, HOUSE_1);
OR
yes(IVORY, HOUSE_1);
yes(GREEN, HOUSE_2); ...
END_EITHER
Obviously fork() would work but probably be too slow.
Creating separate subroutines for each condition would
probably be unacceptable: the code above creates, in
effect, a simple compileable language for problems of
its ilk. Using Prolog instead of C would work, but I'm
asking for C solution.

James Dow Allen

Dec 24 '06 #27
James Dow Allen wrote:
Mr. Clever is probably joking, but I'd be interested to
see what comp.lang.c'ers would come up with if they
rewrote the program shown in
http://groups.google.com/group/rec.p...0f0e2a8cf4ed01
to avoid longjmp().
I don't think that the program would be improved by avoiding longjmp(),
so I'd use it as it is or use the one I wrote years ago, which reads the
items from a text file. (I'm not sure whether it would be appropriate to
post the more than 300 lines here.)

--
Dietmar Schindler
Dec 29 '06 #28

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: malcolm | last post by:
Example, suppose you have these 2 tables (NOTE: My example is totally different, but I'm simply trying to setup the a simpler version, so excuse the bad design; not the point here) CarsSold {...
2
by: aj70000 | last post by:
This is my query select ano,max(date),a_subject from MY_TAB where table_name='xyz' and ano=877 group by a_subject,ano order by a_subject ANO max(Date) A_Subject 877 2005-01-20...
7
by: JJ_377 | last post by:
Can someone tell me why SQL seems to ignore my order by clause? I tried to run through the debugger, but the debugger stops at the select statement line and then returns the result set; so, I have...
27
by: Chris, Master of All Things Insignificant | last post by:
I have come to greatly respect both Herfried & Cor's reponses and since the two conflicted, I wanted to get some clarification. My orginal post: Herfried, maybe your example here can get you to...
3
by: Sean Shanny | last post by:
To all, We are running postgresql 7.4.1 on an G5 with dual procs, OSX 10.3.3 server, 8GB mem, attached to a fully configured 3.5TB XRaid box via fibre channel. I think we have run into this...
26
by: GreatAlterEgo | last post by:
Hi, This is my query which is embedded in a COBOL program. EXEC SQL SELECT DATE, AGE, DURATION, AMT INTO :LDATE, :L.AGE, :L.DURATION, :L.AMT FROM TAB1 WHERE CODE = :KEY.CODE AND...
25
by: metaperl.etc | last post by:
A very old thread: http://groups.google.com/group/comp.lang.python/browse_frm/thread/2c5022e2b7f05525/1542d2041257c47e?lnk=gst&q=for+else&rnum=9#1542d2041257c47e discusses the optional "else:"...
2
by: Jim.Mueksch | last post by:
I am having a problem with using calculated values in a WHERE clause. My query is below. DB2 gives me this error message: Error: SQL0206N "APPRAISAL_LESS_PRICE" is not valid in the context where...
5
by: pwiegers | last post by:
Hi, I'm trying to use the result of a conditional statement in a where clause, but i'm getting 1)nowhere 2) desperate :-) The query is simple: -------- SELECT idUser,...
6
by: jackal_on_work | last post by:
Hi Faculties, I have two queries which give me the same output. -- Query 1 SELECT prod.name, cat.name FROM products prod INNER JOIN categories cat ON prod.category_id = cat.id WHERE cat.id...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.