473,566 Members | 3,273 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Test the validity of each argument in a function

I have a function foo, shown below. Is it a good idea to test each
argument against my assumption? I think it is safer. However, I
notice that people usually don't test the validity of arguments.

For example,
#define MAX_SIZE 100000
int foo(double *x, unsigned ling sz, int option)
{

int val;

if (x == NULL) { /* test against NULL */
printf("foo: x cannot be NULL\n");
exit(EXIT_FAILU RE);
}

if (sz MAX_SIZE) { /* test against too large sz */
printf("foo: sz=%lu too large\n", sz);
exit(EXIT_FAIUL RE);
}

if (option != 0 && option != 1) { /* test against invalid option */
printf("foo: option=%d invalid\n", option);
exit(EXIT_FAILU RE);
}

/* do main things */

return val;
}
Jun 27 '08 #1
4 3282
is*********@gma il.com said:
I have a function foo, shown below. Is it a good idea to test each
argument against my assumption?
Yes, it's a good idea. The action you should take depends on whose fault it
is. If the argument violates the assumption, either the program is wrong
(because it made an incorrect assumption) or the data value is wrong
(because it doesn't meet the criteria for well-formed data).

For example, if you know for sure that your function can't ever be passed
NULL in a pointer argument because the program is designed to prevent
that, and if it *is* passed NULL, then that's a program bug. If, on the
other hand, you're processing a file containing an age field, and the
value stored in it is negative, then clearly that's a data error.

Validate program assumptions with an assertion.

Validate data criteria by handling the error as best you can - typically by
returning an error code to the calling function.

I think it is safer. However, I
notice that people usually don't test the validity of arguments.
Yes, people are lazy like that. Sometimes they don't even use const!
Nevertheless, defensive programming is wise. Just because many people
aren't wise, that doesn't mean you shouldn't be.
For example,
#define MAX_SIZE 100000
int foo(double *x, unsigned ling sz, int option)
{

int val;

if (x == NULL) { /* test against NULL */
printf("foo: x cannot be NULL\n");
exit(EXIT_FAILU RE);
If x can't be NULL because it's *impossible* for x to be NULL, then:

assert(x != NULL);

If x can't be NULL because this would mean the program's input is
incorrect, then return an error code instead, and let your caller worry
about how to handle it.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #2
is*********@gma il.com wrote:
I have a function foo, shown below. Is it a good idea to test each
argument against my assumption? I think it is safer. However, I
notice that people usually don't test the validity of arguments.
The answer depends on how much trust you place in the calling
code. If you're implementing a public library function, then a
check might make sense. If you're writing the calling code
yourself and you trust yourself to not pass invalid values, then
don't waste resources checking what you've already validated.

Your personal programming philosophy plays a role in arriving at
an answer. My own philosophy dictates that invalid values be
detected at input time and not allowed to "pollute" the
correctness of the processing - and to check elsewhere only when
an otherwise valid value might produce undesirable results
(division by zero, tangent of an angle resulting in infinity,
etc).

--
Morris Dovey
DeSoto Solar
DeSoto, Iowa USA
http://www.iedu.com/DeSoto/
Jun 27 '08 #3
On Sat, 12 Apr 2008 07:13:25 -0700 (PDT), is*********@gma il.com
wrote:
>I have a function foo, shown below. Is it a good idea to test each
argument against my assumption? I think it is safer. However, I
notice that people usually don't test the validity of arguments.

For example,
#define MAX_SIZE 100000
int foo(double *x, unsigned ling sz, int option)
nit: ling should be long.
>{

int val;

if (x == NULL) { /* test against NULL */
printf("foo: x cannot be NULL\n");
exit(EXIT_FAILU RE);
}

if (sz MAX_SIZE) { /* test against too large sz */
printf("foo: sz=%lu too large\n", sz);
exit(EXIT_FAIUL RE);
}

if (option != 0 && option != 1) { /* test against invalid option */
printf("foo: option=%d invalid\n", option);
exit(EXIT_FAILU RE);
}

/* do main things */

return val;
}
There are three separate issues here: (A) should you check
arguments, (B) how should you check them, and (C) what should you
do about it if there is an error. Obviously there is quite a bit
of room for variations in style. However here are some
suggestions.

(A) Should you test the validity of the arguments? In general,
the answer is yes. If you do not, an unexpected faulty argument
will produce a mystery bug. These kind of bugs can be doubly
hard to find because (1) you "know" the argument is okay, and (2)
the invalid argument violates the implicit assumptions in the
code.

That said, there are situations where it is reasonable to omit
checks. This can happen when the function is an internal
function within a controlled scope where callers guarantee the
validity of the arguments.

An alternative to checking arguments is to write the code so that
all arguments are valid. Valid may merely mean reporting an
error back to the caller.

(B) How should you test them? In my opinion, the obvious way to
do it is also the worst way to do it if one is programming on any
scale. The obvious way has the form

if (some_condition ) {some_action}

where some_condition is a failure condition, and some_action
typically consists of printing an error message and exiting with
EXIT_FAILURE.

The first thing that is wrong with this kind of code is that it
almost never gets tested adequately. (You, dear reader, always
test your code thoroughly but the TOG, the other guy, doesn't.)

The second thing (minor but a source of problems) is that
condition is backwards; that is, what one should be doing is what
assert does - specify what should be true of the arguments.

Assert is the obvious (and useful) choice for code in a test mode
or for code that is never going to see the light of day outside
of your personal environment. In serious code, however, assert
is inadequate. My choice is to roll my own that is coupled with
an error handler.

(C) What should you do about it if there is an error? There are
a number of things wrong with writing your own action code for
each test: (1) In the nature of things the action code is likely
to be untested; (2) Often the function is the wrong place to
decide what to do; (3) It pre-empts having a coordinated error
management policy.

My policy for programs of any size is to write an error handler
as a program wide utility. The error handler takes care of
writing error reports to an error log file. An error report
includes information about the specific fault and system state
information. The response to the error that it takes depends on
options passed to it. Thus, the default action might simply be
to write an error report and exit. However one could have the
option to pass it a callback function which takes corrective
action and continue. If one creates a my_assert macro, another
option might be to have the function return with an error
indicator to the calling function. Usw.

Your specific strategy might be quite different from mine.
However the main point I am making is that you should have a
coherent error management strategy that is robust and works for
you.
Richard Harter, cr*@tiac.net
http://home.tiac.net/~cri, http://www.varinoma.com
Save the Earth now!!
It's the only planet with chocolate.
Jun 27 '08 #4

<is*********@gm ail.comwrote in message news:
>I have a function foo, shown below. Is it a good idea to test each
argument against my assumption? I think it is safer. However, I
notice that people usually don't test the validity of arguments.

For example,
#define MAX_SIZE 100000
int foo(double *x, unsigned ling sz, int option)
{

int val;

if (x == NULL) { /* test against NULL */
printf("foo: x cannot be NULL\n");
exit(EXIT_FAILU RE);
}

if (sz MAX_SIZE) { /* test against too large sz */
printf("foo: sz=%lu too large\n", sz);
exit(EXIT_FAIUL RE);
}

if (option != 0 && option != 1) { /* test against invalid option */
printf("foo: option=%d invalid\n", option);
exit(EXIT_FAILU RE);
}

/* do main things */

return val;
}

The function will become unreadable if you do that.

Use

assert(x != NULL);
assert(sz <= MAX_SIZE);
assert(option == 0 || option == 1);

instead.
There are legitimate arguments against the semantics of assert, but they are
arguements against the C standard and the conventions now in force.

Almost always you want to take drastic action againt errors. No results are
better than wrong results. The only exception I can think of is video games,
where it does sometimes make sense to suppress errors in the hope that the
game goes on and the program recovers.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 27 '08 #5

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

Similar topics

18
1848
by: alex | last post by:
Hi there, how can I check if a variable is a structure (i.e. a list)? For my special problem the variable is either a character string OR a list of character strings line So how can I test if a variable 'a' is either a single character string or a list? I tried: if a is list:
16
3359
by: jacob navia | last post by:
Valid pointers have two states. Either empty (NULL), or filled with an address that must be at a valid address. Valid addresses are: 1) The current global context. The first byte of the data of the program till the last byte. Here we find static tables, global context pointers, etc. This are the global variables of the program.
13
9530
by: joenuts | last post by:
Is it possible for a function to test one of it's passed in variables (reference to object) for validity? I would like the displayString( string &obString) function to verify that obString 1) exists 2) is a valid string object. calling any methods of said object cause a seg fault if the object doesnt exist. (code to follow) #include...
6
2731
by: Protoman | last post by:
I'm writing a program to calc truth tables of arguments to prove that they are logically valid. Currently, I have to tell the program to print a truth table, and check it by hand to prove it's valid. I'm tired of doing this. I need to write a fn that, given three functions/one function and two variables or anyother combo, run through all four...
33
4525
by: a | last post by:
Hi, I have a pointer that points to an unknown heap memory block, is it possible to check the pointer + 3 is valid or not? If it is impossible, how can I do the check? Thanks
176
8265
by: nw | last post by:
Hi, I previously asked for suggestions on teaching testing in C++. Based on some of the replies I received I decided that best way to proceed would be to teach the students how they might write their own unit test framework, and then in a lab session see if I can get them to write their own. To give them an example I've created the...
40
2699
by: nufuhsus | last post by:
Hello all, First let me appologise if this has been answered but I could not find an acurate answer to this interesting problem. If the following is true: C:\Python25\rg.py>python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) on win32 Type "help", "copyright", "credits" or "license" for more
6
11867
by: blux | last post by:
I am working on a function to check the validity of a sudoku puzzle. It must check the 9x9 matrix to make sure it follows the rules and is a valid sudoku puzzle. this is what I have come up with so far: However I have found that it does not check it correctly. I just need to check the 9x9 array, which I am passing to this function...
7
1441
by: Kevin Raleigh | last post by:
I am currently testing the following browsers on my Debian/Linux system. IE 5, 5.5, 6, Firefox/Iceweasel Opera Is this sufficient for testing web pages? I don't think I need to test for all browsers, and of course using linux there are probably some browsers that I won't be able to test for, but I would appreciate your intelligent...
0
7673
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...
0
7584
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...
0
8109
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7645
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...
0
6263
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...
0
5213
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...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.