473,796 Members | 2,635 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 (permissionErro r)
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 5384
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 (permissionErro r)
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 (permissionErro r)
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 (permissionErro r)
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 (permissionErro r)
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 (permissionErro r)
5:
6: if (data.len() <= 0)
7: return (dataError)
8:
9: write(out, data, data.len)
"Ancient_Hacker " <gr**@comcast.n etwrites:
(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<ope rator) {
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*chr ome.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<ope rator) {
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,cod e) if( Answer == Okay ) if(!cond) Answer =
code; )

(to log all errors)
#define Ensure(cond,cod e) 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

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

Similar topics

5
11509
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 { CarsSoldID int (primary key) MonthID int DealershipID int NumberCarsSold int
2
2363
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 00:00:00.000 Subject_1 877 1900-01-01 00:00:00.000 Subject_2 877 2004-12-20 00:00:00.000 Subject_3
7
2754
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 no idea how it is evaluating the order by clause. THANK YOU! CREATE proc sprAllBooks @SortAscend varchar(4), @SortColumn varchar(10)
27
4718
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 answer a question I've wondered about for a while. With Me.Label1 .Text = ... .Refresh()
3
1870
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 issue before but I thought the code was fixed. :-( I have the following SQL:
26
17215
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 SET = :KEY.SET AND DATE <= :KEY.DATE
25
1877
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:" clause of the for statement. I'm wondering if anyone has ever found a practical use for the else branch?
2
10758
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 it is used. SQLSTATE=42703 SELECT DISTINCT S3.OPR_APPLICATION_NR, S3.APPLICATION_ID, S3.APPRAISAL_TYPE_CD, S3.Appraisal_Used_Amount, S3.RPT_LEVEL2_NR,
5
2666
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, (@ageraw:=YEAR(CURRENT_DATE()) - YEAR(dateofbirth) -
6
3110
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;
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9535
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10465
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10021
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9061
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7558
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6800
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4127
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.