CSC/ECE 517 Fall 2011/ch6 6a am: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 20: Line 20:


By associating pre- and postcondition assertions with a method m,the class tells its clients1
By associating pre- and postcondition assertions with a method m,the class tells its clients1
''
''“If you promise to call m with pre satisfied then I, in return, promise to deliver a final state in which post is satisfied"''<ref> Meyer, Bertrand. Object-Oriented Software Construction, second edition, Prentice Hall, 1997, p. 570</ref>
“If you promise to call m with pre satisfied then I, in return,  
promise to deliver a final state in which post is satisfied"''<ref> Meyer, Bertrand. Object-Oriented Software Construction, second edition, Prentice Hall, 1997, p. 570</ref>


In other words,
In other words,
''
''"Basically programming by contract creates a contract between the software developer and software user - in Meyer's terms 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 (if and only if the preconditions were met). Also, each class has an invariant which must be satisfied after any changes to the object represented by the class. In the other words, the invariant guarantees the object is in a valid state."''<ref>http://www.cs.unc.edu/~stotts/COMP204/contract.html</ref>
"Basically programming by contract creates a contract between the software developer and software user - in Meyer's terms 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 (if and only if the preconditions were met). Also, each class has an invariant which must be satisfied after any changes to the object represented by the class. In the other words, the invariant guarantees the object is in a valid state."<ref>http://www.cs.unc.edu/~stotts/COMP204/contract.html</ref>''
 


===Obligations and benefits===
===Obligations and benefits===


There are two main elements in software system- User and Programmer. In order to understand Obligations and benefits correctly, let us first consider a metaphor and later apply that to Software. The metaphor comes from business life, where a "client" and a "supplier" agree on a "contract" which documents that:
There are two main elements in [http://en.wikipedia.org/wiki/Software Software System]- User and Programmer. In order to understand Obligations and benefits correctly, let us first consider a metaphor and later apply that to Software. The metaphor comes from business life, where a "client" and a "supplier" agree on a "contract" which documents that:


<span style="color:#008080">* The supplier must provide a certain product (obligation) and is entitled to expect that the client has paid its fee (benefit).</span>
<span style="color:#008080">* The supplier must provide a certain product (obligation) and is entitled to expect that the client has paid its fee (benefit).</span>
Line 40: Line 38:
The metaphor relates to a Software System as below:
The metaphor relates to a Software System as below:


<span style="color:#008080">* The programmer must provide the user with a valid outcome(obligation) and can expect that the user has given a correct and valid input(benefit).</span>
<span style="color:#008080">* The [http://en.wikipedia.org/wiki/Programmer Programmer] must provide the user with a valid outcome(obligation) and can expect that the [http://en.wikipedia.org/wiki/User_(computing) User] has given a correct and valid input(benefit).</span>
   
   
<span style="color:#A52A2A">* The User must provide a valid input(obligation) to a method and can expect the programmer to give the correct output(benefit).</span>
<span style="color:#A52A2A">* The [http://en.wikipedia.org/wiki/User_(computing) User] must provide a valid input(obligation) to a method and can expect the [http://en.wikipedia.org/wiki/Programmer Programmer] to give the correct output(benefit).</span>


<span style="color:#483D8B">* Some properties such as stack size discussed earlier are satisfied by the system at all points of time.</span>
<span style="color:#483D8B">* Some properties such as stack size discussed earlier are satisfied by the system at all points of time.</span>
Thus, it is not the responsibility of the Programmer to satisfy the pre-condition. In fact, if the pre-condition is not satisfied by the user, the programmer need not have to do anything. Once the pre-condition is failed, it is not the Programmers' fault even if the system crashes or gives blunders as results.


In order to gain an insight about how programming By Contract actually works, consider the webAssign example from our class:
In order to gain an insight about how programming By Contract actually works, consider the webAssign example from our class:
Line 53: Line 53:


==Programming 'By Contract' in JAVA==
==Programming 'By Contract' in JAVA==
In JAVA, although the exact Programming by contract facility is not provided, it provides an informal "similar" kind of functionality through Programming By Assertions.
===Assertions in Java===
"An [http://en.wikipedia.org/wiki/Assertion_(computing) assertion] is a statement in the [http://en.wikipedia.org/wiki/Java_(programming_language) Java] programming language that enables you to test your assumptions about your program."<ref>http://download.oracle.com/javase/1.4.2/docs/guide/lang/assert.html</ref>
Each assertion contains a [http://en.wikipedia.org/wiki/Boolean_function boolean] expression which we believe should be true. If the boolean expression does not return true, the program throws an error and the further execution of the code is terminated.
There are two forms of assertions in Java:
1. assert Expression;
Here, assert is a keyword and Expression is a Boolean expression. If the expression returns true, the method execution is continued. If the expression returns false, then an AssertionError with no much detail is thrown and the method execution is terminated.
2. assert Expression1 :Expression2;
Here, we use assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError [http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming) constructor], which uses the string representation of the value as the error's detail message.
e.g.
<pre>assert !true : "assert is not true";</pre>
The output will be:
<pre>
Exception in thread "main" java.lang.AssertionError:assert is not true
</pre>


===Example===
===Example===
Consider the following requirement:
The job is to pour water in a glass. The method has to pour water in the glass assuming that glass is not full. This is a precondition and can be checked using a assert statement. After the method is called, the amount of water in the class should be greater than before. This is a postcondition and can be checked by a asseret statement.
<pre>
public class WaterGlass{
boolean isFull;
int water_level;
final int max_level= 10;
WaterGlass()
{
isFull = false;
water_level = 0;
}
// this is the class invariant. This always returns true
public boolean invariant()
{
return ( (this.isFull == true && water_level==max_level)|| ( this.isFull == false && water_level<max_level));
}
//this is the method pourWater
public void pourWater()
{
// Pre Condition. we check that the glass is not full before going into the method.
// If the glass is full, we print the message and stop the function execution.
assert !this.isFull : "Glass is already full. cant fill in more water";
int prev_level = this.water_level;
this.water_level= this.water_level+1;
if(this.water_level == max_level)
{
isFull=true;
}
System.out.println("the water level is " + this.water_level);
// Post Condition. we check that whenever the pre condition is met,
// the new water level is always greater than the original water level
assert this.water_level>prev_level;
}
public static void main(String[] args)
{
WaterGlass myGlass=new WaterGlass();
for(int i=0;i<=10;i++)
{
myGlass.pourWater();
}
}
}
</pre>
==Conclusion==
==Conclusion==
==References:==
==References:==
<references/>
<references/>

Revision as of 02:32, 16 November 2011

Introduction

Writing robust code

Assertions

Pre-Conditions

Post-Conditions

Class Invariants

A class invariant is a predicate that must be true at all points during a program. This is should hold no matter what a method does in the class.

Consider a stack. In a stack, the size should always be greater than 0 and less than the capacity. This should always hold. This property of a stack can neither be represented by a pre-condition nor by a post-condition. Such properties of a class are called as Class invariants.

The useful effect of class invariants in object-oriented software is enhanced in the presence of inheritance. Class invariants are inherited, that is, "the invariants of all the parents of a class apply to the class itself."<ref> Meyer, Bertrand. Object-Oriented Software Construction, second edition, Prentice Hall, 1997, p. 570</ref>

Programming By Contract=

Programming by Contract is known under the name of Design by Contract™ first implemented by Eiffel, a programming language introduced by Bertrand Meyer.It provides the programmers a way to verify that the execution of their methods does not corrupt the state of the data structures.

Definition

According to Bertrand Meyer,

By associating pre- and postcondition assertions with a method m,the class tells its clients1 “If you promise to call m with pre satisfied then I, in return, promise to deliver a final state in which post is satisfied"<ref> Meyer, Bertrand. Object-Oriented Software Construction, second edition, Prentice Hall, 1997, p. 570</ref>

In other words, "Basically programming by contract creates a contract between the software developer and software user - in Meyer's terms 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 (if and only if the preconditions were met). Also, each class has an invariant which must be satisfied after any changes to the object represented by the class. In the other words, the invariant guarantees the object is in a valid state."<ref>http://www.cs.unc.edu/~stotts/COMP204/contract.html</ref>


Obligations and benefits

There are two main elements in Software System- User and Programmer. In order to understand Obligations and benefits correctly, let us first consider a metaphor and later apply that to Software. The metaphor comes from business life, where a "client" and a "supplier" agree on a "contract" which documents that:

* The supplier must provide a certain product (obligation) and is entitled to expect that the client has paid its fee (benefit).

* The client must pay the fee (obligation) and is entitled to get the product (benefit).

* Both parties must satisfy certain obligations, such as laws and regulations, applying to all contracts.<ref>http://www.eiffel.com/developers/design_by_contract.html</ref>

The metaphor relates to a Software System as below:

* The Programmer must provide the user with a valid outcome(obligation) and can expect that the User has given a correct and valid input(benefit).

* The User must provide a valid input(obligation) to a method and can expect the Programmer to give the correct output(benefit).

* Some properties such as stack size discussed earlier are satisfied by the system at all points of time.

Thus, it is not the responsibility of the Programmer to satisfy the pre-condition. In fact, if the pre-condition is not satisfied by the user, the programmer need not have to do anything. Once the pre-condition is failed, it is not the Programmers' fault even if the system crashes or gives blunders as results.

In order to gain an insight about how programming By Contract actually works, consider the webAssign example from our class:

All the students are supposed to give the tests through WebAssign. During the test process, each student is expected to write their answers in the designated text boxes and save the test no more than 4 times. This is as an obligation for the student. The student in turn is ensured that all his answers are correctly recorded and rendered to the professor for evaluation. This is a benefit for the student.

WebAssign is supposed to record the answers given by the student appropriately and render them to the professor for evaluation. This is an obligation for WebAssign. WebAssign is entitled to ensure that the user has answered in the designated text boxes and saved no more than 4 times. This is a benefit to WebAssign.

Programming 'By Contract' in JAVA

In JAVA, although the exact Programming by contract facility is not provided, it provides an informal "similar" kind of functionality through Programming By Assertions.

Assertions in Java

"An assertion is a statement in the Java programming language that enables you to test your assumptions about your program."<ref>http://download.oracle.com/javase/1.4.2/docs/guide/lang/assert.html</ref>

Each assertion contains a boolean expression which we believe should be true. If the boolean expression does not return true, the program throws an error and the further execution of the code is terminated.

There are two forms of assertions in Java:

1. assert Expression; Here, assert is a keyword and Expression is a Boolean expression. If the expression returns true, the method execution is continued. If the expression returns false, then an AssertionError with no much detail is thrown and the method execution is terminated.

2. assert Expression1 :Expression2; Here, we use assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.

e.g.

assert !true : "assert is not true";

The output will be:

Exception in thread "main" java.lang.AssertionError:assert is not true

Example

Consider the following requirement:

The job is to pour water in a glass. The method has to pour water in the glass assuming that glass is not full. This is a precondition and can be checked using a assert statement. After the method is called, the amount of water in the class should be greater than before. This is a postcondition and can be checked by a asseret statement.

public class WaterGlass{
	boolean isFull;
	int water_level;
	final int max_level= 10;
	WaterGlass()
	{
		isFull = false;
		water_level = 0;
	}
	// this is the class invariant. This always returns true
	public boolean invariant()
	{
		
		return ( (this.isFull == true && water_level==max_level)|| ( this.isFull == false && water_level<max_level));
				 
	}
	//this is the method pourWater
	public void pourWater()
	{
			// Pre Condition. we check that the glass is not full before going into the method.
			// If the glass is full, we print the message and stop the function execution.
			assert !this.isFull : "Glass is already full. cant fill in more water";
	
			int prev_level = this.water_level;
			this.water_level= this.water_level+1;
			if(this.water_level == max_level)
			{
				isFull=true;
			}
			System.out.println("the water level is " + this.water_level);
			
			// Post Condition. we check that whenever the pre condition is met, 
			// the new water level is always greater than the original water level
			
			assert this.water_level>prev_level;
	}
	public static void main(String[] args)
	{
		WaterGlass myGlass=new WaterGlass();
		
		for(int i=0;i<=10;i++)
		{
			myGlass.pourWater();
		}
	}
}


Conclusion

References:

<references/>