Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating function arguments?

On a regular basis, I validate my function arguments:


public static void Function(int i, string s)
{
  Debug.Assert(i > 0);
  Debug.Assert(s != null);
  Debug.Assert(s.length > 0);
}

Of course the checks are "valid" in the context of the function.

Is this common industry practice? What is common practice concerning function argument validation?

like image 965
user62572 Avatar asked Feb 04 '09 20:02

user62572


1 Answers

The accepted practice is as follows if the values are not valid or will cause an exception later on:

if( i < 0 )
   throw new ArgumentOutOfRangeException("i", "parameter i must be greater than 0");

if( string.IsNullOrEmpty(s) )
   throw new ArgumentNullException("s","the paramater s needs to be set ...");

So the list of basic argument exceptions is as follows:

ArgumentException
ArgumentNullException
ArgumentOutOfRangeException
like image 91
Robert Paulson Avatar answered Oct 23 '22 03:10

Robert Paulson