For example I have the following code:
public class Calc(){
final int PI = 3.14; //is this an invariant?
private int calc(int a, int b){
return a + b;
//would the parameters be pre-conditions and the return value be a post-condition?
}
}
I am just confused on what exactly these terms mean? The code above is what I think it is, however can anyone point me into the right direction with my theory?
Your code is in a contract with other bits and pieces of code. The pre-condition is essentially what must be met initially in order for your code to guarantee that it will do what it is supposed to do.
For example, a binary search would have the pre-condition that the thing you are searching through must be sorted.
On the other hand, the post-condition is what the code guarantees if the pre-condition is satisfied. For example, in the situation of the binary search, we are guaranteed to find the location of what we were searching for, or return -1 in the case where we don't find anything.
The pre-condition is almost like another thing on top of your parameters. They don't usually affect code directly, but it's useful when other people are using your code, so they use it correctly.