Presentation is loading. Please wait.

Presentation is loading. Please wait.

Karlstad University Computer Science Design Contracts and Error Management Design Contracts and Errors A Software Development Strategy Eivind J. Nordby.

Similar presentations


Presentation on theme: "Karlstad University Computer Science Design Contracts and Error Management Design Contracts and Errors A Software Development Strategy Eivind J. Nordby."— Presentation transcript:

1 Karlstad University Computer Science Design Contracts and Error Management Design Contracts and Errors A Software Development Strategy Eivind J. Nordby Software Engineering Research Group Computer Science Karlstad University

2 Computer Science Design Contracts and Error Management Contract principles, page 2 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 Method Precondition Postcondition SupplierClient Obligation: Assure precondition Benefit: Assume postcondition Benefit: Assume precondition Obligation: Assure postcondition Interface Offered Required

3 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 3 Design Contracts: Basic Principles SupplierClient Precondition met SupplierClient Precondition not met Correct Postcondition met ! QIQO Postcondition not met ? Correct GIGO result undefined

4 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 4 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

5 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 5 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(); }

6 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 6 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();

7 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 7 Different Styles of Implementing a Function Stack implementation in defensive programming Object 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]; }

8 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 8 not OK Weak vs. Strong Contracts Weak contract Any input accepted successfailure OK Double responsibility not qualifiedqualified Qualified input required Client responsibility Strong contract

9 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 9 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

10 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 10 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?

11 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 11 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)

12 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 12 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)

13 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 13 Partly Executable Contracts for Stack top A weak contract Pre:true Post:this = if not then result = top element else EmptyException thrown A strong contract Pre:not empty Post:this = result = top element

14 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 14 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 s ize() Define a suitable contract for this method Discuss the consequences of your contract for the client and for the supplier?

15 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 15 Exercise 3 A moment of reflection: What are Contracts Good for? Look in appendix A for some ideas ? ??? generate more paperwork?

16 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 16 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

17 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 17 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

18 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 18 In class Menu loop from first item compare current item with parameter until parameter item found return 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

19 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 19 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 ListNode first next ObjectNode next Object data

20 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 20 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

21 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 21 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

22 Karlstad University Computer Science Design Contracts and Error Management Appendix A Suggested answers to the exercises

23 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 23 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

24 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 24 Suggested Solution to Exercise 3 Benefits from applying contracts 1Design support tool –Contributes to a better design 2Documentation tool –The contracts for a module describe the module 3Maintenance tool –The contracts for a module identify how changes affect clients 4Error detection tool –Requires language support –Discussed in Appendix C

25 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 25 Benefits from Applying Contracts 1Design 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 2Documentation 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

26 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 26 Benefits from Applying Contracts 3Maintenance 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 4Error 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

27 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 27 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 be 0 < 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

28 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 28 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

29 Karlstad University Computer Science Design Contracts and Error Management Appendix B What Happens if the Precondition is not Satisfied?

30 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 30 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

31 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 31 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 list Object getElement(int position) { if(Compilation.ASSERT_IS_ON) Assert.isTrue(positionOK(position)); return elements[position]; }

32 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 32 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

33 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 33 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

34 Karlstad University Computer Science Design Contracts and Error Management Appendix C Case study examples From a project programmed in C

35 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 35 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.

36 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 36 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.

37 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 37 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?

38 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 38 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 listThe list header. nodeThe node to insert predThe 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

39 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 39 Exempel 1: Kommentarer till (2) Beskrivningen har kortats av till bara funktionalitet Inflätade villkor h ar 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.

40 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 40 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.

41 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 41 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 nodeThe node to remove Precondition node is contained in a list Postcondition node is not contained in any list

42 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 42 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

43 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 43 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.

44 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 44 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 listThe 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

45 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 45 Exempel 3: Kommentarer till (2) Betoningen har lagts på beskrivningen Inflätade villkor h ar 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.

46 Karlstad University Computer Science Design Contracts and Error Management Appendix D External and internal errors and their contracts

47 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 47 A system part exposes interfaces –External or internal External and Internal Interfaces System part Supplier Internal interface External interface

48 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 48 Some possible sources of external errors External Interfaces Software Components The System Hardware Components Data Bases Error End Users Other System

49 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 49 Some possible sources of internal errors Internal Interfaces Programmers Error Program Fault Violation Designers Error Design Fault Violation The system

50 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 50 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

51 Karlstad University Computer Science Design Contracts and Error Management Contract principles, page 51 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


Download ppt "Karlstad University Computer Science Design Contracts and Error Management Design Contracts and Errors A Software Development Strategy Eivind J. Nordby."

Similar presentations


Ads by Google