Budgeting of investments Eivind Tandberg Brasilia April 25, 2005.
Karlstad University Computer Science Design Contracts and Error Management Design Contracts and...
-
Upload
janet-brittingham -
Category
Documents
-
view
214 -
download
0
Transcript of Karlstad University Computer Science Design Contracts and Error Management Design Contracts and...
Karlstad UniversityComputer Science
Design Contracts andError Management
Design Contracts and ErrorsA Software Development Strategy
Eivind J. Nordby
Software Engineering Research Group
Computer Science
Karlstad University
Contract principles, page 2Karlstad UniversityComputer Science
Design Contracts andError Management
Contracts - Preconditions and Postconditions
• In module design, the obligations and benefits of the contracts are regulated through preconditions and postconditions
• Note– There is always a contract, even when not explicitly expressed
MethodPrecondition
Postcondition
SupplierClient
Obligation:• Assure
precondition
Benefit:• Assume
postcondition
Benefit:• Assume
precondition
Obligation:• Assure
postcondition
InterfaceOfferedRequired
Contract principles, page 3Karlstad UniversityComputer Science
Design Contracts andError Management
Design Contracts: Basic Principles
SupplierClient
Preconditionmet
SupplierClient
Preconditionnot met
Correct
Postconditionmet
!QIQO
Postconditionnot met
?
Correct
GIGOresult undefined
Contract principles, page 4Karlstad UniversityComputer Science
Design Contracts andError Management
Some Details about the Class Stack
• Assume that these functions are defined for a stack:– top() returns a reference to the topmost element on the stack
• the element itself is unaffected by the operation
• the element remains on the stack
– size() returns the number of elements currently on the stack
• Assume these implementation details about a stack:– the stack is implemented using an array called elements– topIndex is the index of the topmost element on the stack
Contract principles, page 5Karlstad UniversityComputer Science
Design Contracts andError Management
Different Styles of Calling a Function
• Obtaining the top element of a stack– defensive programming, with no explicit contract
Implicit precondition for top: true
• Client code
...pushes and pops...
try {
anElement = myStack.top();
}
catch(stackEmptyException sEE)
{
printErrorMessage();
}
Contract principles, page 6Karlstad UniversityComputer Science
Design Contracts andError Management
Different Styles of Calling a Function
• Obtaining the top element of a stack– offensive programming, with an explicit, strong contract
Precondition for top: !isEmpty()
• Client code
...pushes and pops...
if(!myStack.isEmpty())
anElement = myStack.top()
else
printErrorMessage();
Contract principles, page 7Karlstad UniversityComputer Science
Design Contracts andError Management
Different Styles of Implementing a Function
• Stack implementation in defensive programmingObject top() throws IndexOutOfBoundsException
{
if (size() > 0)
return elements[topIndex];
else
throw(new IndexOutOfBoundsException());
}
• Stack implementation in offensive programming– Based on an explicit, strong contract
Object top()
{
return elements[topIndex];
}
Contract principles, page 8Karlstad UniversityComputer Science
Design Contracts andError Management
not OK
Weak vs. Strong Contracts
Weak contract
Any input accepted
successfailure
OK
Double responsibility
not qualified qualified
Qualified input
required
Client responsibility
Strong contract
Contract principles, page 9Karlstad UniversityComputer Science
Design Contracts andError Management
• Reducing the number of faults and saving time
• Reducing the number of faults and saving time
• Strong contracts should be used whenever possible
• Weak contracts– Are needed where a correct call cannot be assured
• Providing an open-ended exit
• Strong contracts– Simplifies the solution by reducing complexity
– Simplifies error detection by allocating responsibilities
Comparison
Contract principles, page 10Karlstad UniversityComputer Science
Design Contracts andError Management
Exercise 1
• The following is one possible implementation of the operation top:Object top() throws EmptyException
{
if (size() > 0)
return elements[topIndex];
else
throw(new EmptyException());
}
• Part 1: Identify the contract implicitly defined by this method– That is: Specify its precondition and postcondition
• Part 2: Try to suggest another contract– How is this new contract different from the first one?
Contract principles, page 11Karlstad UniversityComputer Science
Design Contracts andError Management
Suggested Answer to Exercise 1, part 1
• In this example, no particular requirements are placed on the client. The client is allowed to call top in all situations, including when there is no top element to return.
• Precondition:– true
• that is, there is no requirement, the precondition is always satisfied
• Postcondition:– If the stack is not empty, then the topmost element is returned, else
(that is, if the stack is empty), then an exception is thrown
– The stack is unchanged • optional postcondition, otherwise implicit (specify changes only)
Contract principles, page 12Karlstad UniversityComputer Science
Design Contracts andError Management
Suggested Answer to Exercise 1, part 2
• Another contract for top could be
• Precondition:– The stack is not empty
• Postcondition:– The topmost element of the stack is returned– The stack is unchanged
• optional postcondition, otherwise implicit (specify changes only)
Contract principles, page 13Karlstad UniversityComputer Science
Design Contracts andError Management
Partly Executable Contracts for Stack top
• A weak contractPre: true
Post: this = this@pre,if not empty@prethen result = top elementelse EmptyException thrown
• A strong contractPre: not empty
Post: this = this@pre, result = top element
Contract principles, page 14Karlstad UniversityComputer Science
Design Contracts andError Management
Exercise 2: Contract Definition
• The list operation getElement(int position) should return the element at the given position of a list– Positions are counted from 1– The total number of elements are given by the function size()
• Define a suitable contract for this method
• Discuss the consequences of your contract for the client and for the supplier?
Contract principles, page 15Karlstad UniversityComputer Science
Design Contracts andError Management
Exercise 3
A moment of reflection:
What are Contracts Good for?
Look in appendix A for some ideas
? ???
???generate morepaperwork?
Contract principles, page 16Karlstad UniversityComputer Science
Design Contracts andError Management
Exercise 4: Contract Implementation
• Assume that the list is implemented using an array of Objects– Declared as Object[] stackArray = new Object[MaxSize]
• Implement the contract from Exercise 2– getElement(int position) should return the element at the given
position of a list
– Positions are counted from 1
• Precondition: – Informal: position is ok.– Executable: (0 < position) && (position <= size())
• Postcondition:– The the object at the given position is returned
Contract principles, page 17Karlstad UniversityComputer Science
Design Contracts andError Management
• Strong contracts were applied in the Business Logic interface
• Example from class Menu– Get the details for an item in a menu
• To be edited by the end user
– MenuItem getItem(itemId)– Called from a user menu display
• Contract– Precondition: the menu item searched exists in the menu– Postcondition: the details about the menu item are returned
Example from a Case Study
Contract principles, page 18Karlstad UniversityComputer Science
Design Contracts andError Management
• In class Menuloop from first itemcompare current item with parameter
until parameter item foundreturn the details of the current item
• Exploiting the strong contracts– Precondition loop runs at least once– Precondition item found before end of list
Implementation of getItem(itemId)
• Contract violation detection– Java’s built-in runtime control– “Index out of bounds”, “Null pointer” exceptions
Contract principles, page 19Karlstad UniversityComputer Science
Design Contracts andError Management
Exercise 5: Alternative implementation of getElement
• Assume that the list is implemented using a linked list
– The List class has a reference first to the first node in the list
– Each node has a reference next to the next node in the list
– Each node has a reference data to the data value of that node
• Repeat exercise 4 for this data structure
– The data object at the selected position should be returned
List
Node
first
next
Object
Node
next
Object
data
Contract principles, page 20Karlstad UniversityComputer Science
Design Contracts andError Management
Underhåll av programvara
• När en modul utvecklas finns alltid en risk att specifikationerna förändras ”bara lite grann”
• Ev. förändringar måste göras explicita• Vilka förändringar kan göras utan att klienten påverkas
och när är en funktion de facto omdefinierad?– Det finns semantiska regler för detta– De är inte svåra, men måste ändå genomgås och förstås
Contract principles, page 21Karlstad UniversityComputer Science
Design Contracts andError Management
Summary of Aspects for Semantic Integrity
• Interfaces, clients and suppliers– Contracts, preconditions, postconditions, invariants
• Required and offered interfaces• Syntax and semantics• No, intuitive, structured, executable and formal
semantics• Visible and invisible states• Responsibilities and benefits• External and internal errors• Weak and strong contracts
– Type inheritance and type violation
• Error detection and error handling• Static and dynamic contract violation detection
Karlstad UniversityComputer Science
Design Contracts andError Management
Appendix A
Suggested answers to the exercises
Contract principles, page 23Karlstad UniversityComputer Science
Design Contracts andError Management
Suggested Solution to Exercise 2
Object getElement(int position)
• Precondition: – Informal: position is ok.– Executable: 0 < position && position <= listSize()
• Postcondition– The element at the given position is returned
Contract principles, page 24Karlstad UniversityComputer Science
Design Contracts andError Management
Suggested Solution to Exercise 3
Benefits from applying contracts
1 Design support tool– Contributes to a better design
2 Documentation tool– The contracts for a module describe the module
3 Maintenance tool– The contracts for a module identify how changes affect clients
4 Error detection tool– Requires language support– Discussed in Appendix C
Contract principles, page 25Karlstad UniversityComputer Science
Design Contracts andError Management
Benefits from Applying Contracts
1 Design support tool– Help during design to find and express the module specifications
– Useful to design quality into the product • An alternative to debugging the errors out if it
– This is the most important benefit from contracts
2 Documentation tool– The contracts for a module specify the requirements on the
module
– Useful to both the module user and its programmer
– javadoc can produce documentation directly from comments in the code
Contract principles, page 26Karlstad UniversityComputer Science
Design Contracts andError Management
Benefits from Applying Contracts
3 Maintenance tool– A modification of an implementation within the definition of the
current contract does not affect clients
– A modification of a contract to one that is stronger does not affect clients
– A modification of a contract to one that is weaker does affect clients. It defines a new function
4 Error detection tool– When a condition is executable, it may be verified by the software
itself• Error detection is not error handling
– Requires language support
– Further discussed in Appendix B
Contract principles, page 27Karlstad UniversityComputer Science
Design Contracts andError Management
Suggested Solution to Exercise 4
Object getElement(int position){
return stackArray[position - 1];
}
• No checking of the boundaries is needed– That is taken care of by the precondition
• The precondition states that position should be0 < position && position <= listSize()– This implies that indexing goes from 1 as seen from the outside
• Inside the method, the indexing goes from zero– The index has to be adjusted when passing from the external to
the internal view
Contract principles, page 28Karlstad UniversityComputer Science
Design Contracts andError Management
Suggested Solution to Exercise 5
public Object getElement(int position){ Node temp = first; int i = 1; // Index of temp while(i < position) temp = temp.getNext(); i++; // termination guaranteed by pre
// i == position, temp -> sought element return temp.getData();} // getElement
Karlstad UniversityComputer Science
Design Contracts andError Management
Appendix B
What Happens if the Precondition is not Satisfied?
Contract principles, page 30Karlstad UniversityComputer Science
Design Contracts andError Management
Different Strategies for Handling Violated Preconditions
• Since the client has not kept its part of the contract, the supplier has no obligations whatsoever
• The supplier can do whatever it wants
• Two possible strategies
– Do nothing special• try to perform the task in the normal way• hope that the system will die :-)
– Trap the violation and make the system die• exit (or throw an undocumented runtime exception)• possibly dump an error code to a log file
Contract principles, page 31Karlstad UniversityComputer Science
Design Contracts andError Management
An Example of Handling Precondition Violations
• getElement method in a list– The precondition states that position should be ok– If the position is not ok, the system will still survive as long as
position is within the array boundaries.– One approach is to trap the violation and make the system die to
notify the developer to correct the error in the client code
// Pre: positionOK(position)// Post: the selected element is returned from the
listObject getElement(int position){
if(Compilation.ASSERT_IS_ON)Assert.isTrue(positionOK(position));
return elements[position];
}
Contract principles, page 32Karlstad UniversityComputer Science
Design Contracts andError Management
Do Not Try to Handle the Error
• Do not handle errors and allow the system to go on– The client should not be aware of any exceptions that might be thrown.
It could be tempted to catch it and thereby allow the error to live on
– Documenting an error exception would implement a different contract than the one specified for the method
• The client is not aware of the test– From the client’s point of view, there is no “security net”
– The test can be removed without affecting the contract since it is not part of the contract
• There is no recovery from the error– The only measure taken if the precondition is violated is to exit the
system
– It is an error trap, not an error handling
Contract principles, page 33Karlstad UniversityComputer Science
Design Contracts andError Management
Rules for Precondition Violation Traps
• The trap should be completely transparent to the client– No return value to test or exception to catch
– A trap causes the program to die when it detects an error
• The user should develop the client code without resorting to the traps– The traps may be disabled or enabled without his knowledge
• The supplier code should produce the same result with a trap as without it– The program may be run with traps enabled or disabled
– The trap should not affect the behavior of the system in any way
– In particular, the trap should not change any variables
Karlstad UniversityComputer Science
Design Contracts andError Management
Appendix C
Case study examplesFrom a project programmed in C
Contract principles, page 35Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 1: Befintlig specifikation
• Insert a node (1) Syntax
void Insert(struct List* list, struct Node* node, struct Node* pred);
Description The Insert() function is used for inserting a new node into any position in a list.
It always inserts the node after the specified node that already is a part of the list. This function also handles the special cases when adding to the head of list and to the tail of list. There are other functions which handle the special cases more efficiently.
Parameters list
The list header. node
The node to insert pred
The list element after which “node” should be inserted. Return values
None.
Contract principles, page 36Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 1: Markerad befintlig specifikation
• Insert a node (1) Syntax
void Insert(struct List* list, struct Node* node, struct Node* pred);
Description The Insert() function is used for inserting a new node into any position in a list.
It always inserts the node after the specified node that already is a part of the list. This function also handles the special cases when adding to the head of list and to the tail of list. There are other functions which handle the special cases more efficiently.
Parameters list
The list header. node
The node to insert pred
The list element after which “node” should be inserted. Return values
None.
Contract principles, page 37Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 1: Kommentarer till (1)
• Beskrivning av funktion, villkor och resultat inbakat.– inserts the node after the specified node (eftervillkor)
– … that already is a part of the list (förvillkor)
• Ger en otydlig bild av användningen– Hur lägger man in en nod längst fram?
– “There are other functions which handle the special cases more efficiently.” Varför inte tala om vilka?
Contract principles, page 38Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 1: Alternativt förslag
• Insert a node (2) Syntax
void Insert(struct List* list, struct Node* node, struct Node* pred);
Description Inserts a new node at a specific position in a list. AddHead and AddTail are the
preferred methods for inserting a node at the beginning or at the end of the list. Parameters
list The list header. node The node to insert pred The list element after which “node” should be inserted.
Precondition Newlist has been called for list node is not contained in of any list pred is contained in list or NULL
Postcondition node is contained in the list after pred, or at the beginning if pred==NULL
Contract principles, page 39Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 1: Kommentarer till (2)
• Beskrivningen har kortats av till bara funktionalitet
• Inflätade villkor har ersatts av för- resp. eftervillkor• Tydlig åtskillnad på parameterbeskrivning och villkor• Förvillkor
– Det generella förvillkoret att listan måste ha initierats har gjorts explicit
– Specialfallet ”pred == null” har uttryckligen tillåtits• Eftervillkor
– Resultatet, även specialfallet, har gjorts explicit i eftervillkoret• Rubriken Return values har tagits bort.
– Om den behövs ersätts den av Postcondition, som är mer generell.
Contract principles, page 40Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 2: Befintlig specifikation
• Remove a node Syntax
void Remove(struct Node* node); Description
The Remove() function will remove a specified node from a list. Be sure to specify a node in a list otherwise unpredictable events could occur.
• Parameters node
The list element to remove Return values
None.
Contract principles, page 41Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 2: Kommentarer
• Förvillkoret måste vara uppfyllt– annars är resultatet oförutsägbart Be sure to specify a node in a list otherwise unpredictable events could occur.– detta anges bara sporadiskt för just den här
funktionen• Alternativ specifikation Syntax
void Remove(struct Node* node); Description
Removes a node from the list it is contained in. Parameters
node The node to remove Precondition
node is contained in a list Postcondition
node is not contained in any list
Contract principles, page 42Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 3: Befintlig specifikation
• Initialize list (1)• Syntax
void NewList(struct List* list);• Description
Before the list can be used it has to be initialized. This function resets the list to an empty state. Note that the Type structure remains uninitialized. See "List initialization" on page 146.
• Parameters list
The list header.
• Return values None
Contract principles, page 43Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 3: Kommentarer till (1) Description
• Innehåller inte bara en beskrivning av funktionen, utan även en överordnad förklaring till användningssättet.– ”Before the list is used …” hör hemma under rubrik ”Guidelines
for use” eller liknande t.ex. före Include Files.• Ger en otydlig bild av användningen
– “resets the list to an empty state” kan tyda på att funktionen kan användas för att tömma en befintlig lista, vilket är fel
• Innehåller irrelevant information– Note that the Type structure remains uninitialized.
• Symptom på sammanblandning av list-egenskaper och elementinnehåll
– See "List initialization" on page 146.• Syftar till implementationsdetaljer, hör inte hit.
Contract principles, page 44Karlstad UniversityComputer Science
Design Contracts andError Management
• Initialize list (2)
• Syntax void NewList(struct List* list);
• Description Initializes the list structure prior to all use. Should be called
once after creation of the list and then never again for the same list. (The data structure Type and Pad are not affected).
• Parameters list The list header.
• Precondition NewList has not been called for the list.
• Postcondition The list is ready for use, i.e. list may be used as argument to
the other list management functions in this package.
Exempel 3: Alternativt förslag
Contract principles, page 45Karlstad UniversityComputer Science
Design Contracts andError Management
Exempel 3: Kommentarer till (2)
• Betoningen har lagts på beskrivningen
• Inflätade villkor har ersatts av förvillkor• Irrelevant information har tonats ner eller tagits bort
– Type• En variabel som anger innehållets datatyp.• Modulen skulle behöva designas om med renare semantiska linjer.
Listfunktioner blandas med användningsfunktioner.
– "List initialization" on page 146• Otydlig målgrupp: implementerare eller användare?• Implementationsdetaljer blandas med gränssnittsbeskrivning. För
användarna öppnar det upp för för mycket av implementations-detaljerna, uppmuntrar till ”White box”-användning.
• För lite inkapsling, gynnar inte modularitet.
Karlstad UniversityComputer Science
Design Contracts andError Management
Appendix D
External and internal errors and their contracts
Contract principles, page 47Karlstad UniversityComputer Science
Design Contracts andError Management
• A system part exposes interfaces– External or internal
External and Internal Interfaces
System part
Supplier Internalinterface
Externalinterface
Contract principles, page 48Karlstad UniversityComputer Science
Design Contracts andError Management
• Some possible sources of external errors
External Interfaces
SoftwareComponents
The System
HardwareComponents
Data Bases
Error
Error
Error
End Users
OtherSystem
Contract principles, page 49Karlstad UniversityComputer Science
Design Contracts andError Management
• Some possible sources of internal errors
Internal Interfaces
Programmers
Error Program Fault
Violation
Designers
ErrorDesign Fault
Violation
The system
Contract principles, page 50Karlstad UniversityComputer Science
Design Contracts andError Management
• External errors– Committed by end users or external systems
• Databases, external components, hardware
– Cause violation of external interfaces
• Internal errors– Committed by developers– Result in faults in the software– Cause violation of internal interfaces
External and Internal Errors
• On a permanent basis, consistent until the software is corrected
• On a per use basis, varying from case to case
Contract principles, page 51Karlstad UniversityComputer Science
Design Contracts andError Management
• External errors– Correct input cannot be assured– wrong input should be handled and the user informed– Best managed by weak contracts
• Internal errors– Correct input can be assures– System faults should be detected
• And corrected by the responsible author
– Best managed by strong contracts
Correspondence Contracts Errors