Example. Adding specs to contains

[comp1110-1A]

We can take the contains function from Example [comp1110-16] and annotate it with a specification. It holds no assumptions about the input parameters, so the function has no nontrivial preconditions. Its postcondition, however, captures the notion of correctness for this function:

/** Returns if an integer is contained in an integer array @param haystack is an integer array @param needle is the integer we want to search for @return true iff there exists some j such that haystack[j] == needle */ boolean contains(int[] haystack, int needle) { int i = 0; while(i < haystack.length) { // i <= haystack.length && forall 0 <= j < i, haystack[j] != needle if(needle == haystack[i]) { return true; } i = i + 1; } // i == haystack.length // forall 0 <= j < haystack.length, haystack[j] != needle return false; }

Note how the loop invariant, allows us to reason that our postcondition (the @return clause above) is satisfied by our function.

bars magnifying-glass caret-down plus minus arrow-right xmark