user3496101
user3496101

Reputation: 303

Explanation of Pre-conditions and Post-Conditions?

My latest assignment requires me to have this follow criteria

"All methods have explicit postcondition and those with parameters preconditions "

I have read through a few web pages trying to explain pre/post conditions, but can seem to get a grasp on them, could someone explain to me what they are, their use and how to write them?

Thanks

(the language i am learning is C# by the way)

Upvotes: 2

Views: 5565

Answers (3)

Urler
Urler

Reputation: 520

Preconditions must be true before you enter the method, otherwise the contract is nullified. Postcoditions should be true after you exit the method. I'm sorry I don't know C# but if you know Java this selection sort example might help. Example:

public static void selSort(int[] a, int b) {
    //Pre-condition: array a is not null and size of unsorted section is bigger than 1.
    for(int unsortSz = b; unsortSz >1; unsortSz--) {
        int max = 0;
        for (int p = 1; p < unsortSz; p++){
            if (a[p] > a[max]){
                max = p;
            }
        }

        //Post-condition: max is the position of largest element in unsorted part. 

        // now just swap the last element in unsorted part with max
        temp = a[unsortSz-1];
        a[unsortSz] = a[max];
        a[max] = temp;
    }
}

Upvotes: 5

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

This is all a part of Code Contract. When entering a method or property the preconditions should be met. Whereas postconditions are expectations at the time the method or property code exits. From the MSDN

Preconditions specify state when a method is invoked. They are generally used to specify valid parameter values. All members that are mentioned in preconditions must be at least as accessible as the method itself; otherwise, the precondition might not be understood by all callers of a method.

Postconditions are contracts for the state of a method when it terminates. The postcondition is checked just before exiting a method. The run-time behavior of failed postconditions is determined by the runtime analyzer.

Also check this excellent article Preconditions, Postconditions: Design by Contract for C#

Upvotes: 3

Zohaib Aslam
Zohaib Aslam

Reputation: 595

the conditions before calling the method are called precoditions like the name of method, the type of parameters and the number of parameters etc. postconditions are the condition that are at the end of the method like a method with return type float must return a float not an int and etc.

Upvotes: 1

Related Questions