I recalled my first year of college (five years ago) when I passed the exam to take computer science out of the intro-level. The question arose about loop invariants, and I was wondering if cycle invariants were needed in this case, or if the question was just a bad example ... the question was to write an iterative definition for a factor function, and then prove that the function is correct.
The code I provided for the factorial was as follows:
public static int factorial(int x) { if ( x < 0 ){ throw new IllegalArgumentException("Parameter must be >= 0"); }else if ( x == 0 ){ return 1; }else{ int result = 1; for ( int i = 1; i <= x; i++ ){ result*=i; } return result; } }
My own proof of correctness was a case-by-case proof, and in each I claimed that it was correct by definition (x! Is undefined for negative values, 0! Is 1, and x! 1 * 2 * 3 ... * x for positive x value). The professor wanted me to prove the cycle using the cycle invariant; however, my argument was that it was "by definition" correct, since the definition of "x!" for a positive integer, x is "the product of integers from 1 ... x", and the for-loop in the else clause is just a literal translation of this definition. Is the cycle invariant really necessary as proof of correctness in this case? How complicated should the loop be before the loop invariant (and the correct initialization and termination conditions) needed to prove the correctness?
Also, I was wondering ... how often is such formal evidence used in the industry? I found that about half of my courses are very theoretical and evidence-based, and about half are very realistic and coding, without any formal or theoretical materials. How much do they overlap in practice? If you use evidence in the industry, when do you use it (always, only if it's difficult, rarely, never)?
Edit
If we ourselves are convinced that part of the code is correct, can convince others (unofficially) that this is correct, and there are single tests in place, to what extent are formal proofs of correctness necessary?
language-agnostic
Michael Aaron Safyan
source share