<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Mabanz</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Mabanz"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Mabanz"/>
	<updated>2026-05-22T01:18:44Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=56151</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=56151"/>
		<updated>2011-11-22T03:25:22Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditions]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch6_6a_pc#Preconditions preconditions], [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch6_6a_pc#Postconditions postconditions], and [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch6_6a_pc#Invariants invariants] when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly [http://en.wikipedia.org/wiki/Assertion_(computing) assertions] can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where [http://www.cprogramming.com/tutorial/exceptions.html normal error handling] is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) [http://www.ece.cmu.edu/~koopman/des_s99/sw_testing/#concepts Correctness] - system's ability to perform its job according to the specification and 2) [http://en.wikipedia.org/wiki/Robustness_%28computer_science%29 Robustness] - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. [http://en.wikipedia.org/wiki/Type_system#Static_typing Static typing], for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly [http://msdn.microsoft.com/en-us/library/ee787088.aspx Garbage collection] helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, Reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. [http://en.wikipedia.org/wiki/Subtype_polymorphism Polymorphism] also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch6_6a_pc#Preconditions precondition] that must be satisfied by the consumer of the routine. And each feature ends with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch6_6a_pc#Postconditions postconditions] which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from [http://www.amazon.com/Object-Oriented-Design-Using-Java-Skrien/dp/0072974168 Skrien]):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch6_6a_pc#Languages_with_Native_Support Eiffel]). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] and [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Defensive_programming Defensive programming] on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
[http://msdn.microsoft.com/library/z1zx9t92 C#] 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the [http://en.wikipedia.org/wiki/Halting_problem halting problem].&amp;lt;ref&amp;gt;http://www.efgh.com/math/impossible.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://c2.com/cgi/wiki?HaltingProblemDiscussions&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55922</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55922"/>
		<updated>2011-11-18T05:06:46Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Contract and Inheritance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly [http://en.wikipedia.org/wiki/Assertion_(computing) assertions] can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] and [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Defensive_programming Defensive programming] on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
[http://msdn.microsoft.com/library/z1zx9t92 C#] 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the [http://en.wikipedia.org/wiki/Halting_problem halting problem].&amp;lt;ref&amp;gt;http://www.efgh.com/math/impossible.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://c2.com/cgi/wiki?HaltingProblemDiscussions&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55921</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55921"/>
		<updated>2011-11-18T05:06:17Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Contract and Inheritance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly [http://en.wikipedia.org/wiki/Assertion_(computing) assertions] can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Defensive_programming Defensive programming] on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
[http://msdn.microsoft.com/library/z1zx9t92 C#] 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the [http://en.wikipedia.org/wiki/Halting_problem halting problem].&amp;lt;ref&amp;gt;http://www.efgh.com/math/impossible.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://c2.com/cgi/wiki?HaltingProblemDiscussions&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55920</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55920"/>
		<updated>2011-11-18T05:03:34Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Comparison with Defensive Programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly [http://en.wikipedia.org/wiki/Assertion_(computing) assertions] can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Defensive_programming Defensive programming] on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
[http://msdn.microsoft.com/library/z1zx9t92 C#] 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the [http://en.wikipedia.org/wiki/Halting_problem halting problem].&amp;lt;ref&amp;gt;http://www.efgh.com/math/impossible.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://c2.com/cgi/wiki?HaltingProblemDiscussions&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55918</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55918"/>
		<updated>2011-11-18T04:47:53Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Assertions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly [http://en.wikipedia.org/wiki/Assertion_(computing) assertions] can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
[http://msdn.microsoft.com/library/z1zx9t92 C#] 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the [http://en.wikipedia.org/wiki/Halting_problem halting problem].&amp;lt;ref&amp;gt;http://www.efgh.com/math/impossible.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://c2.com/cgi/wiki?HaltingProblemDiscussions&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55917</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55917"/>
		<updated>2011-11-18T04:46:11Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Languages with Native Support */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
[http://msdn.microsoft.com/library/z1zx9t92 C#] 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the [http://en.wikipedia.org/wiki/Halting_problem halting problem].&amp;lt;ref&amp;gt;http://www.efgh.com/math/impossible.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://c2.com/cgi/wiki?HaltingProblemDiscussions&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55916</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55916"/>
		<updated>2011-11-18T04:45:03Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Static Checking */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the [http://en.wikipedia.org/wiki/Halting_problem halting problem].&amp;lt;ref&amp;gt;http://www.efgh.com/math/impossible.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://c2.com/cgi/wiki?HaltingProblemDiscussions&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55915</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55915"/>
		<updated>2011-11-18T04:41:02Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Static Checking */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the [http://en.wikipedia.org/wiki/Halting_problem halting problem].&amp;lt;ref&amp;gt;http://www.efgh.com/math/impossible.htm&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55914</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55914"/>
		<updated>2011-11-18T04:37:46Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Static Checking */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the [http://en.wikipedia.org/wiki/Halting_problem halting problem].&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55913</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55913"/>
		<updated>2011-11-18T04:36:11Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Static Checking */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java&amp;lt;ref&amp;gt;http://www.eecs.umich.edu/~bchandra/courses/papers/Flanagan_ESC.pdf&amp;lt;/ref&amp;gt; offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55912</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55912"/>
		<updated>2011-11-18T04:35:23Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Static Checking */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/magazine/hh335064.aspx&amp;lt;/ref&amp;gt; and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55911</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55911"/>
		<updated>2011-11-18T04:34:17Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Languages with Native Support */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&amp;lt;ref&amp;gt;http://msdn.microsoft.com/en-us/library/dd264808.aspx&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55910</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55910"/>
		<updated>2011-11-18T04:31:36Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Languages with Native Support */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract_in_detail.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55909</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55909"/>
		<updated>2011-11-18T04:29:37Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Languages with Native Support */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; &amp;lt;ref&amp;gt; http://java.sun.com/developer/technicalArticles/JavaLP/assertions/ &amp;lt;/ref&amp;gt;  statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to [http://www.eiffel.com/ Eiffel]; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55906</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55906"/>
		<updated>2011-11-18T04:27:22Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&amp;lt;ref&amp;gt;http://mindprod.com/jgloss/assertions.html&amp;lt;/ref&amp;gt; Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55905</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55905"/>
		<updated>2011-11-18T04:21:08Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s.&amp;lt;ref&amp;gt;Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986&amp;lt;/ref&amp;gt; Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an &amp;lt;code&amp;gt;assert&amp;lt;/code&amp;gt; statement in Java or &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
For example, suppose you have the following code in your method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        // Execution should never reach this point!!!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rather than just leaving a comment, you could add an assert statement as follows:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    void foo() {&lt;br /&gt;
        for (...) {&lt;br /&gt;
            if (...)&lt;br /&gt;
                return;&lt;br /&gt;
        }&lt;br /&gt;
        assert false; // Execution should never reach this point!&lt;br /&gt;
    } &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This will throw an AssertionError when the program reaches that unexpected point of execution. This enables the programmer to catch any irregularities in the code at any stage of development, making the process of debugging very easy. Similarly assertions can be used to verify the preconditions, postconditions and class invariants in a method. You can assert that preconditions hold good at the start of the method, and that postcondition and class invariant hold good at the end of method execution. This ensures that contract is always being satisfied by both the supplier and the client. Of course having assert statements incurs overhead, for instance, if we have to perform some clean-up in case the post condition is not met. So most of the programming languages provide a means to disable the assertions at runtime. E.g in Java, you could use: &amp;lt;code&amp;gt;  -disableassertions or -da switch&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Note that assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Hence it would be unwise to use assertions where normal error handling is necessary. Assertions should only be used to document logically impossible situations and discover programming errors.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55896</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55896"/>
		<updated>2011-11-18T04:09:29Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Languages with Native Support */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language.&amp;lt;ref&amp;gt;http://www.eiffel.com/developers/design_by_contract.html&amp;lt;/ref&amp;gt; When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55895</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55895"/>
		<updated>2011-11-18T04:08:37Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Invariants */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: a linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55893</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55893"/>
		<updated>2011-11-18T04:08:04Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Preconditions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55889</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55889"/>
		<updated>2011-11-18T04:07:26Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Static Checking */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the [http://www.eiffel.com/ Eiffel programming language].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;staticChecking&amp;quot;&amp;gt;Static Checking&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55888</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55888"/>
		<updated>2011-11-18T04:06:45Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Languages with Native Support */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the [http://www.eiffel.com/ Eiffel programming language].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;nativeSupport&amp;quot;&amp;gt;Languages with Native Support&amp;lt;/div&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55887</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55887"/>
		<updated>2011-11-18T04:06:05Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase [[ #reliability | software reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the [http://www.eiffel.com/ Eiffel programming language].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55886</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55886"/>
		<updated>2011-11-18T04:05:44Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Software Reliability */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software [[ #reliability | reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the [http://www.eiffel.com/ Eiffel programming language].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== &amp;lt;div id=&amp;quot;reliability&amp;quot;&amp;gt;Software Reliability&amp;lt;/div&amp;gt; ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55885</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55885"/>
		<updated>2011-11-18T04:05:08Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Assertions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software [[ #reliability | reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the [http://www.eiffel.com/ Eiffel programming language].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;assertions&amp;quot;&amp;gt;Assertions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55884</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55884"/>
		<updated>2011-11-18T04:04:27Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditions | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software [[ #reliability | reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the [http://www.eiffel.com/ Eiffel programming language].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55882</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55882"/>
		<updated>2011-11-18T04:03:40Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditons | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software [[ #reliability | reliability]] by creating explicit specifications for each method. Contract violations can be detected early on using [[ #assertions | assertions]] or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among others have [[ #nativeSupport | native support]] for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform [[ #staticChecking | static checking]] at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the [http://www.eiffel.com/ Eiffel programming language].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55851</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55851"/>
		<updated>2011-11-18T03:39:06Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Preconditions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditons | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the [http://www.eiffel.com/ Eiffel programming language].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55849</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55849"/>
		<updated>2011-11-18T03:37:02Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Invariants */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditons | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;invariants&amp;quot;&amp;gt;Invariants&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55848</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55848"/>
		<updated>2011-11-18T03:36:41Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Postconditions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditons | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;postconditions&amp;quot;&amp;gt;Postconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55842</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55842"/>
		<updated>2011-11-18T03:34:50Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditons | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariants | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55841</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55841"/>
		<updated>2011-11-18T03:34:28Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditons | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain [[ #postconditions | postconditions]] are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a [[ #invariant | class invariant]]. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55837</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55837"/>
		<updated>2011-11-18T03:31:13Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Preconditions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditons | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;div id=&amp;quot;preconditions&amp;quot;&amp;gt;Preconditions&amp;lt;/div&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55836</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55836"/>
		<updated>2011-11-18T03:30:00Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain [[ #preconditons | preconditons]] are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55831</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55831"/>
		<updated>2011-11-18T02:53:24Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Invariants */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_invariant class invariant] is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55830</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55830"/>
		<updated>2011-11-18T02:52:40Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Postconditions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Postcondition postcondition] is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55829</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55829"/>
		<updated>2011-11-18T02:49:13Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Preconditions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Precondition precondition] is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55828</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55828"/>
		<updated>2011-11-18T02:46:42Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;.&amp;lt;ref&amp;gt;http://www.cs.usfca.edu/~parrt/course/601/lectures/programming.by.contract.html&amp;lt;/ref&amp;gt; The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55827</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55827"/>
		<updated>2011-11-18T02:42:25Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Topical References ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55826</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55826"/>
		<updated>2011-11-18T02:40:26Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by [http://en.wikipedia.org/wiki/Bertrand_Meyer Bertrand Meyer] in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55825</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55825"/>
		<updated>2011-11-18T02:39:34Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_by_contract Programming by contract] is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011&amp;diff=55824</id>
		<title>CSC/ECE 517 Fall 2011</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011&amp;diff=55824"/>
		<updated>2011-11-18T02:07:42Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[[Link title]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a ms]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a cs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a ri]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a lj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1b sa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1b ds]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1b tj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1c cm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1c sj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1c ka]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1d sr]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e vs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e aa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a sc]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e dm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e an]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e sa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e lm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1g vn]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1f rs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1f sv]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1g jn]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1h ps]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e sm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1i zf]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1g rn]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1i cl]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1d ss]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1i lj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1h hs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1d gs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2b ns]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2b jp]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2a av]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2f jm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2e ad]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2e kt]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2e gp]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2b qu]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2c bs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2c rs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2a ca]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2b rv]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2c ds]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2b sa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2f mm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2f vh]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2e ps]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 3a oe]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 3h rr]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 3h ss]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 4b js]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 4b ms]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4b ds]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4i aa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4i sd]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4d mt]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4d ls]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4d ch]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4c ap]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4h sv]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4e cl]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4e gs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4a ga]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4f sl]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4i js]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4f ss]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4c dm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4g as]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4g nv]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4g ms]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4h kp]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4h as]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4j fw]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4f rs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4i lc]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch17 5b uo]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch17 5b br]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch5 5d he]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch5 6d ny]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6d sk]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6e ch]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6b ss]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6b ra]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6c sj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6a am]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6e zj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE_517_Fall_2011/ch6 6e gm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6f jd]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6f va]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6c p]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6e gm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6c sm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch18 6a sc]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch18 6d na]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch6 6a pc]]&lt;br /&gt;
&lt;br /&gt;
*[[trial]]&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55475</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55475"/>
		<updated>2011-11-17T07:40:02Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Comparison with Defensive Programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Programming by contract is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55474</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55474"/>
		<updated>2011-11-17T07:39:04Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Languages with Native Support */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Programming by contract is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Programming by Contract ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== When not to use Programming by Contract === &lt;br /&gt;
Asserts and &amp;quot;by contract&amp;quot; specifications catch programmer errors not run-time errors! (Add more details)&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value when declaring a postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Code Contracts also support class invariants. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;. The class invariant method is called after the execution of every public method in the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;br /&gt;
&lt;br /&gt;
In addition to runtime contract checking, some libraries offer static checking at compile time as well. These tools can catch contract violations without even running the code. C# code contracts and the Extended Static Checker (ESC) for Java offer just that. Static analysis has theoretic limitations due to it being equivalent to the halting problem.&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55473</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55473"/>
		<updated>2011-11-17T07:24:51Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* C# */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Programming by contract is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Programming by Contract ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== When not to use Programming by Contract === &lt;br /&gt;
Asserts and &amp;quot;by contract&amp;quot; specifications catch programmer errors not run-time errors! (Add more details)&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''' C# '''&lt;br /&gt;
&lt;br /&gt;
C# 4.0 has native support for code contracts via the System.Diagnostics.Contract library. Preconditions are introduced with a call to &amp;lt;code&amp;gt;Contract.Requires&amp;lt;/code&amp;gt; and postconditions with a call to &amp;lt;code&amp;gt;Contract.Ensures&amp;lt;/code&amp;gt;. Code contracts also allow the programmer to access the return value in the postcondition.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void Add(int num1, int num2)&lt;br /&gt;
{&lt;br /&gt;
    Contract.Requires(num1 &amp;gt; 0);&lt;br /&gt;
    Contract.Requires(num2 &amp;gt; 0);&lt;br /&gt;
&lt;br /&gt;
    return num1 + num2;&lt;br /&gt;
&lt;br /&gt;
    Contract.Ensures(Contract.Result&amp;lt;int&amp;gt;() &amp;gt; 0);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Class invariants are also supported. An invariant method must be decorated with the &amp;lt;code&amp;gt;ContractInvariantMethod&amp;lt;/code&amp;gt; attribute and contain only calls to &amp;lt;code&amp;gt;Contract.Invariant&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
[ContractInvariantMethod]&lt;br /&gt;
protected void ObjectInvariant () &lt;br /&gt;
{&lt;br /&gt;
    Contract.Invariant ( this.y &amp;gt;= 0 );&lt;br /&gt;
    Contract.Invariant ( this.x &amp;gt; this.y );&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Runtime Checking ===&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55472</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55472"/>
		<updated>2011-11-17T07:10:53Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Eiffel */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Programming by contract is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Programming by Contract ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== When not to use Programming by Contract === &lt;br /&gt;
Asserts and &amp;quot;by contract&amp;quot; specifications catch programmer errors not run-time errors! (Add more details)&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
''' Eiffel '''&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
=== Runtime Checking ===&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55471</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55471"/>
		<updated>2011-11-17T07:10:13Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Languages with Native Support */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Programming by contract is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Programming by Contract ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== When not to use Programming by Contract === &lt;br /&gt;
Asserts and &amp;quot;by contract&amp;quot; specifications catch programmer errors not run-time errors! (Add more details)&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
=== Eiffel ===&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
=== Runtime Checking ===&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55470</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55470"/>
		<updated>2011-11-17T07:09:20Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Programming by contract is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Programming by Contract ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== When not to use Programming by Contract === &lt;br /&gt;
Asserts and &amp;quot;by contract&amp;quot; specifications catch programmer errors not run-time errors! (Add more details)&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Runtime Checking ===&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55469</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55469"/>
		<updated>2011-11-17T07:09:00Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;6a (was 5c).  Lecture 18, Programming by contract.  My notes for Lecture 18 are largely taken from 20-year-old articles by Bertrand Meyer.  The principles are timeless, but there are undoubtedly new embellishments that would provide better background to the topics discussed in the lecture.  Write a narrative, generally following the lecture organization, that explains programming by contract in more detail.&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Programming by contract is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance. Languages such as Eiffel and C# (via the System.Diagnostics.Contract library) among other have native support for contracts. C# Code Contracts and the Extended Static Checker (ESC) for Java have the ability to perform static checking at compile time to determine if a possible run-time contract exception can occur. This feature is limited due to the fact that it is equivalent to the halting problem.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Programming by Contract ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== When not to use Programming by Contract === &lt;br /&gt;
Asserts and &amp;quot;by contract&amp;quot; specifications catch programmer errors not run-time errors! (Add more details)&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Runtime Checking ===&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55468</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55468"/>
		<updated>2011-11-17T06:54:17Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;6a (was 5c).  Lecture 18, Programming by contract.  My notes for Lecture 18 are largely taken from 20-year-old articles by Bertrand Meyer.  The principles are timeless, but there are undoubtedly new embellishments that would provide better background to the topics discussed in the lecture.  Write a narrative, generally following the lecture organization, that explains programming by contract in more detail.&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Programming by contract is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract aims to increase software reliability by creating explicit specifications for each method. Contract violations can be detected early on using assertions or similar means. A contract violation indicates a potential bug in the code. Many languages allow these assertions to be used when debugging and turned off in production to increase performance.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Programming by Contract ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== When not to use Programming by Contract === &lt;br /&gt;
Asserts and &amp;quot;by contract&amp;quot; specifications catch programmer errors not run-time errors! (Add more details)&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Runtime Checking ===&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55467</id>
		<title>CSC/ECE 517 Fall 2011/ch6 6a pc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch6_6a_pc&amp;diff=55467"/>
		<updated>2011-11-17T06:45:00Z</updated>

		<summary type="html">&lt;p&gt;Mabanz: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;6a (was 5c).  Lecture 18, Programming by contract.  My notes for Lecture 18 are largely taken from 20-year-old articles by Bertrand Meyer.  The principles are timeless, but there are undoubtedly new embellishments that would provide better background to the topics discussed in the lecture.  Write a narrative, generally following the lecture organization, that explains programming by contract in more detail.&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Programming by contract is a paradigm used in software design that was first introduced by Bertrand Meyer in the 1980s. Programming by contract defines a contractual relationship between the caller of a method and the method itself. It is analogous to a business relationship where both parties must meet certain obligations but also receive benefits. In terms of programming by contract, the caller is know as the &amp;quot;client&amp;quot; and the method being called is known as the &amp;quot;supplier&amp;quot;. The client must ensure that certain preconditons are met before calling the supplier. The supplier benefits from not having to check the arguments itself. The supplier in return must ensure that certain postconditions are met. The client benefits from knowing that it received what it expected. Another concept, also part of programming by contract, is a class invariant. A class invariant is a condition that must be true throughout the lifetime of each instance of that class.&lt;br /&gt;
&lt;br /&gt;
Programming by contract&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
&lt;br /&gt;
=== Preconditions ===&lt;br /&gt;
&lt;br /&gt;
A precondition is a condition that must be true prior to calling a method for which it is defined. Preconditions bind the caller of that method, that is, it is the responsibility of the caller to ensure that the preconditions are satisfied. The method is not responsible, nor expected, to check the preconditions. The output from the method is not defined for the case where the preconditions are violated. In that case the method could crash the system, go into an infinite loop, or do nothing at all.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; block constitutes a precondition in the Eiffel programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= are23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Postconditions ===&lt;br /&gt;
&lt;br /&gt;
A postcondition is a condition that must be true after execution of the method for which it is defined. Postconditions bind the method itself. The method is responsible for ensuring that these conditions are met. The caller of the method is guaranteed that the postconditions will hold if the original preconditions were satisfied when calling the method.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; block constitutes a postcondition in Eiffel.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
set_hour (a_hour: INTEGER)&lt;br /&gt;
            -- Set `hour' to `a_hour'&lt;br /&gt;
        require&lt;br /&gt;
            valid_argument: 0 &amp;lt;= a_hour and a_hour &amp;lt;= 23&lt;br /&gt;
        do&lt;br /&gt;
            hour := a_hour&lt;br /&gt;
        ensure&lt;br /&gt;
            hour_set: hour = a_hour&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Invariants ===&lt;br /&gt;
&lt;br /&gt;
A class invariant is a condition that must hold true throughout the lifetime of an object. It is a condition imposed on the class itself rather than a method of that class. Class invariants are often checked before and after the execution of each method in that class. An object found in a state where the invariant does not hold, would indicate a bug in the system.&lt;br /&gt;
&lt;br /&gt;
An example of a class invariant: A linked list has an instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; that stores the number of nodes in the list. &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; should always equal the actual number of nodes in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class LinkedList {&lt;br /&gt;
    private Node head;&lt;br /&gt;
    private int length;  // length stores a cached version of the number of nodes. It should always equal the actual number of nodes.&lt;br /&gt;
    &lt;br /&gt;
    public LinkedList() {&lt;br /&gt;
        head = null;&lt;br /&gt;
        length = 0;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public getLength() {&lt;br /&gt;
        return length;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void Add(int value) {&lt;br /&gt;
        Node n = new Node(value);&lt;br /&gt;
&lt;br /&gt;
        if(head == null) {&lt;br /&gt;
            head = n;&lt;br /&gt;
        }&lt;br /&gt;
        else {&lt;br /&gt;
            Node current = head;&lt;br /&gt;
&lt;br /&gt;
            while(current.getNext() != null) {&lt;br /&gt;
                current = current.getNext();&lt;br /&gt;
            }&lt;br /&gt;
            current.setNext(n);&lt;br /&gt;
            n.setPrevious(current);&lt;br /&gt;
        }&lt;br /&gt;
        length++;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /* other methods omitted */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Along with Preconditions and Postconditions, class invariants provide another means to write good code. Class invariants come to the fore when we look at guidelines for writing methods. We typically have two types of methods : accessors, that simply retrieve a value and modifiers, that modify the object on which they are called. There is an important guideline for modifier methods to observe if they are to do their jobs well: &amp;quot;Public methods should always keep objects in a well-formed state.&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Here, well-formed state seems like a very subjective term.  A good way to specify what makes objects of a class well-formed is to list the class invariants. A class invariant is a statement about the state of objects of the class between public method calls.&lt;br /&gt;
&lt;br /&gt;
The Following example illustrates the usage and importance of class invariants. &lt;br /&gt;
For the LinkedList class, the following could be the class invariants:&lt;br /&gt;
&lt;br /&gt;
#The value of instance variable &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; is always equal to the number of elements on the list. &lt;br /&gt;
#The &amp;lt;code&amp;gt;next&amp;lt;/code&amp;gt;  instance variable of the last node on the list must have null or some other special placeholder object as its value.&lt;br /&gt;
&lt;br /&gt;
With the first invariant, it is clear that we have to initialize &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; to 0 in the constructor and update it appropriately in &amp;lt;code&amp;gt; add &amp;lt;/code&amp;gt;  and &amp;lt;code&amp;gt; remove &amp;lt;/code&amp;gt; methods. This will prevent any bugs from creeping into the code and in case they did, debugging becomes much simpler. &lt;br /&gt;
Similarly the second invariant makes sure that the linked list is well terminated. Otherwise a user traversing the list could end up writing at illegal memory location. Hence class invariants are valuable tools in writing good code. &lt;br /&gt;
&lt;br /&gt;
'''How do we identify class invariants?'''&lt;br /&gt;
&lt;br /&gt;
Since class invariants describe the state of an object between method calls, one easy way to identify them is to look at the instance variables of the class, since instance variables hold the state of an object. This has an implication that, many instance variables can lead to many Invariants and hence make it hard to debug. One should look at the trade-off between performance and the number of class invariants when deciding on adding instance variables.&lt;br /&gt;
For instance, in the LinkedList example, not having &amp;lt;code&amp;gt;_length&amp;lt;/code&amp;gt; instance variable would help us reduce the number of invariants, but this would mean that user will have to traverse the list each time he needs to count the number of items on the list.&lt;br /&gt;
&lt;br /&gt;
=== Assertions ===&lt;br /&gt;
&lt;br /&gt;
It is useful to check preconditions, postconditions, and invariants when debugging code. A violation of which constitutes a bug in the system. This can be accomplished using an assert statement in Java or Contract.Requires statement in C# 4.0. These programming features can be used to alert the programmer of bugs in development and can be turned off in production.&lt;br /&gt;
&lt;br /&gt;
== Software Reliability ==&lt;br /&gt;
A major concern in software design is Reliability, which depends on two factors: 1) Correctness - system's ability to perform its job according to the specification and 2) Robustness - handling abnormal conditions. Reliability is especially important in Object oriented software because of the additional complexity imposed by Reusability. Some of the common problems encountered when writing software include: &lt;br /&gt;
* System failure - CPU crash, Disk/Memory access errors, Network errors&lt;br /&gt;
* Invalid input data - Out of range data, Bad file name,etc.&lt;br /&gt;
* Programming errors - Memory leaks, Buffer overruns, etc.  &lt;br /&gt;
&lt;br /&gt;
There are many programming language features that help tackle these issues. Static typing, for example, is a major help for catching inconsistencies before they have had time to become bugs. Similarly Garbage collection helps to remove the specter of devious memory management errors.  Various software design methodologies also come handy when dealing with complex software. For instance, reusability itself can help eliminate lots of bugs, if we are reusing existing code that has already been thoroughly tested and deployed. Polymorphism also helps in handling issues related to maintainability by reducing the size of the code and making it more elegant. But in a large and complex software involving multiple developers, we need a more systematic approach of specifying and implementing object-oriented software elements and their interactions. This is exactly what  &amp;quot;Programming by contract&amp;quot; promises to do. &lt;br /&gt;
&lt;br /&gt;
=== Programming by contract ===&lt;br /&gt;
Basically programming by contract creates a contract between the software developer and software user, which are referred to as the supplier and the consumer. Every feature, or method, starts with a precondition that must be satisfied by the consumer of the routine. And each feature ends with postconditions which the supplier guarantees to be true after it is executed(if and only if the preconditions were met). Consider the following example of a static Intersect() method on a Set object (Quoted from Skrien 4.6):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public static Set intersect(Set s1, Set s2)&lt;br /&gt;
  Precondition: s1 and s2 are not null.&lt;br /&gt;
  Postcondition: &lt;br /&gt;
    Returns a Set with the common elements of s1 and s2, if s1 and s2 are not null.&lt;br /&gt;
    If s1 or s2 is null, an IllegalArgumentException is thrown.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note here that this documentation is not overly specific about the implementation nor is it very general and vague. This can be stated concisely as a guideline:&lt;br /&gt;
&amp;quot;The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow&lt;br /&gt;
all implementations that are acceptable&amp;quot;. are&lt;br /&gt;
&lt;br /&gt;
Also, the above contract does not mention anything about the behavior of the method when preconditions are not satisfied. This is Meyer’s non-redundancy principle: &amp;quot;Under no circumstances shall the body of a routine ever test for the routine’s precondition&amp;quot;. This implies that if the preconditions are not met, the behavior of the method is undefined (it could crash, throw an exception, or run in an infinite loop, etc.).&lt;br /&gt;
&lt;br /&gt;
(Does it fit here?)&lt;br /&gt;
In essence, this theory suggests associating a specification with every software element. These specifications (or contracts) govern the interaction of the element with the rest of the world. This is different from having a formal specification in that the specification language is embedded in the design and programming language (e.g. Eiffel). This makes it possible to use a single notation and a single set of concepts throughout the software life cycle, and since these are modeled based on the programming language itself, it provides a great deal of clarity about the requirements at each stage of software development.&lt;br /&gt;
&lt;br /&gt;
=== Contract and Inheritance ===&lt;br /&gt;
An important implication of Programming by Contract is when Inheritance and polymorphism are involved.  Subtype polymorphism means: &amp;quot;If S is a subtype of T,then any term of type S can be safely used in a context where a term of type T is expected&amp;quot;. In case of object oriented programming, type is defined by a class and inheritance enables us to define subtypes of a class (If Base class defines a type, the Derived class becomes a subtype). In this situation, the Derived class should fully honor the Base class contract. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
Suppose you are given a class List, that has a public interface: &amp;lt;code&amp;gt; insert(Item const&amp;amp; x) &amp;lt;/code&amp;gt;.&lt;br /&gt;
And suppose you have to implement a new class SortedList, and provide insert method with the same signature. Isn't is obvious that SortedList be made a subclass of List and override the insert() method?. The answer is no!. &lt;br /&gt;
&lt;br /&gt;
To decide whether we can override the List::insert() method, we will have to look at the Contract promised by this method. Suppose the base class insert() method has advertised its contract as &amp;quot;Promises a copy of Item will be inserted somewhere within this List&amp;quot;. In this case the derived class can override this, since this is a weak post-condition which can be strengthened in the derived class. So the derived class insert() can say that &amp;quot;Promises a copy of Item will be inserted in the sorted order within this List&amp;quot; and no contract is broken. &lt;br /&gt;
&lt;br /&gt;
Suppose, instead the Base class method has a strong post condition: &amp;quot;Promises a copy of Item will be inserted at the end of this List&amp;quot;. Then the derived class cannot override this, since derived class cannot guarantee that the Item will be inserted at the end, hence a breach of Contract. &lt;br /&gt;
&lt;br /&gt;
'''So why bother with all this Contract business?''' &lt;br /&gt;
&lt;br /&gt;
Consider in the above example (strong post-condition case), suppose the derived class breaches the contract and overrides insert() anyway. Now a user who was using the List::insert() method assumes that the items are added at the end, i.e sorted based on time of insertion. But suppose he accidentally calls SortedList::insert() through the base class List pointer, then the Item would be inserted somewhere in-between based on the value it contains, rather than the time of insertion. This will surely introduce hard-to-find bugs in the code, which is the problem this principle was designed to solve. Liskov's substitution principle that deals with the Base-Derived relationship can be rephrased based on this understanding: &lt;br /&gt;
&lt;br /&gt;
It is acceptable to subclass B from a class A, if for every public method with identical signatures in A and B, &lt;br /&gt;
#Pre-conditions for B's method are no stronger than preconditions for A's method&lt;br /&gt;
#Post-conditions for B's method are no weaker than postconditions for A's method&lt;br /&gt;
&lt;br /&gt;
== Comparison with Defensive Programming ==&lt;br /&gt;
Restating the crux of &amp;quot;Programming by contract&amp;quot;: &amp;quot;The supplier class guarantees postconditions of its methods as long as client guarantees that preconditions of those methods are met&amp;quot;. This implies that if the client fails to satisfy the preconditions, the behavior of supplier is undefined, meaning it could result in an Exception being thrown, or a system crash. &lt;br /&gt;
&lt;br /&gt;
Defensive programming on the other hand, augments this guideline as - &amp;quot;Try to make your methods do something appropriate in all cases so that there are no preconditions&amp;quot;. You know errors are almost certainly going to occur and illegal input is going to be given to methods, so make sure that your methods can defend against such input by doing something explicit in a way that is helpful to the user of those methods. &lt;br /&gt;
&lt;br /&gt;
However, this approach could introduce major performance hit. For instance, consider a method that performs binary search on an integer array. A precondition for such a method is that the array is sorted. To eliminate this precondition, the binary search method could first check the array to see if it is sorted and, if not, throw an exception. However, in that case the method’s efficiency is reduced from O(log n) to O(n), where n is the array size.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Programming by Contract ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== When not to use Programming by Contract === &lt;br /&gt;
Asserts and &amp;quot;by contract&amp;quot; specifications catch programmer errors not run-time errors! (Add more details)&lt;br /&gt;
&lt;br /&gt;
== Languages with Native Support ==&lt;br /&gt;
&lt;br /&gt;
Design by contract is central to Eiffel; it is built into the language. When using inheritance to override a method, one may only weaken the preconditions not strengthen them. Thus a call to any method of a subclass is guaranteed to meet the preconditions of the parent class. Conversely, postconditions can only be strengthened in an overridden method so that the results guaranteed by the parent class will still be met by the base class.&lt;br /&gt;
&lt;br /&gt;
Eiffel uses the &amp;lt;code&amp;gt;require&amp;lt;/code&amp;gt; keyword to introduce preconditions and the &amp;lt;code&amp;gt;ensure&amp;lt;/code&amp;gt; keyword to introduce postconditions. If a precondition or postcondition is violated, an exception is thrown. Exception handling is not used for control flow or for invalid data input. In Eiffel, one can handle an exception using the &amp;lt;code&amp;gt;rescue&amp;lt;/code&amp;gt; keyword. Inside the exception handling section, the &amp;lt;code&amp;gt;retry&amp;lt;/code&amp;gt; keyword may be used to execute the method again.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
connect_to_server (server: SOCKET)&lt;br /&gt;
      -- Connect to a server or give up after 10 attempts.&lt;br /&gt;
    require&lt;br /&gt;
        server /= Void and then server.address /= Void&lt;br /&gt;
    local&lt;br /&gt;
        attempts: INTEGER&lt;br /&gt;
    do&lt;br /&gt;
        server.connect&lt;br /&gt;
    ensure&lt;br /&gt;
      connected: server.is_connected&lt;br /&gt;
    rescue&lt;br /&gt;
        if attempts &amp;lt; 10 then&lt;br /&gt;
            attempts := attempts + 1&lt;br /&gt;
            retry&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Runtime Checking ===&lt;br /&gt;
&lt;br /&gt;
=== Static Checking ===&lt;/div&gt;</summary>
		<author><name>Mabanz</name></author>
	</entry>
</feed>