As it is written, calling factorial( -1 )
N == 0
) would never be reached.
Eventually the computer system would run out of resources,
and the program would stop running.
int factorial( int N ) { if ( N == 0 ) return 1; else return N * factorial( N-1 ) ; }
Defensive programming is when the programmer anticipates
problems and writes code to deal with them.
To avoid the disaster a negative parameter would cause,
sometimes factorial()
is written like this:
int factorial( int N ) { if ( N <= 0 ) return 1; else return N * factorial( N-1 ) ; }
But, according to the math-like definition, this is not correct.
The value of factorial( -1 )
Sometimes the method is written to throw an exception when an illegal argument is detected. But this adds complication since now the caller must deal with a possible exception.
Perhaps the best solution is to write factorial()