Contracts

Semla Design Method
for use in Skywalker
A Design Method with a Focus on Semantic Descriptions
Karlstad University
Ericsson Infotech AB
NUTEK
Karlstad University
Dept. of Computer Science
2000-05-09
Improved software quality through
semantic descriptions (Skutt)
What is this Course About?
•
•
•
A university research project (Skutt) for software improvement is
going on since 1999
– in cooperation with Ericsson Infotech here in Karlstad
– supported by NUTEK
• the Swedish National Board for Industrial and Technical
Development
A design method for improved software quality (Semla) has been
developed
– focusing on the description of the semantics
– based on contracts
• the terms will be explained shortly
The project leader team for Skywalker Services has decided to apply
the method in the Skywalker Services
– as a complement to RUP
Karlstad University
Dept. of Computer Science
Semla 2
Course Objectives
After this course, you should
•
Have a common understanding of what a design contract is
•
Have a common understanding of how to use contracts during
design and implementation
•
Be able to use contracts in your work for Skywalker
Karlstad University
Dept. of Computer Science
Semla 3
Coarse Grained Course Plan
•
09.00-10.00 Lecture part 1 and 2
•
10.00-10.15 Coffee
•
10.15-11.15 Lecture part 3
•
11.15-11.20 Short break
•
11.20-12.20 Lecture part 4
•
12.20-12.30 Course summary
Karlstad University
Dept. of Computer Science
Semla 4
Course Overview
•
Part 1: Positioning Semla in the context of system development
– The big picture of system development with RUP
– Reported problem areas for system development
•
Part 2: How to define a module with contracts
– Modularity
– Contracts - preconditions and postconditions
– Contracts - allocation of responsibilities
– Contracts - description of the semantics of module interfaces
– What contracts are good for
– Example and discussion
Karlstad University
Dept. of Computer Science
Semla 5
Course Overview (continued)
•
Part 3: How to use a module defined with contracts
– How the users of a module can benefit from contracts
– Different styles of calling a function with and without contracts
– Example and discussion
•
Part 4: How to implement a module defined with contracts
– How the programmers of a module can benefit from contracts
– Different programming styles with and without contracts
– Discussion and exercise
•
Course summary
– The paradox of guaranteeing more by checking less
•
Appendices
Karlstad University
Dept. of Computer Science
Semla 6
Before We Start
•
•
•
•
•
System development is a team work
Which is better?
– Microscopic view:
• “I should always protect my
module against crashes”
– Macroscopic view
• “I should always protect the
system against defects”
The overall goal is to make the system
work well
That can be done by
– Avoiding errors in the first place
– Detecting and removing errors that sneak in
Surviving an error is not a goal
– Errors should be detected and removed
Karlstad University
Dept. of Computer Science
Semla 7
Part 1
Positioning Semla in System Development
Identifying the Primary Areas of Impact of Semla
Karlstad University
Dept. of Computer Science
2000-05-09
Improved software quality through
semantic descriptions (Skutt)
The Big Picture of System Development with RUP
Inception
Elaboration
Construction
Transition
Requirements
Analysis
Design
Implementation
Test
Iterations
Karlstad University
Dept. of Computer Science
Iter #1
#2
Iter #3
Semla 9
#4
#5
#6
Iter #7
#8
The Largest Software Problems
A survey from the European Software Process Improvement Training Initiative
(ESPITI):
The relative importance of various types of software problems in industry: 3800 responses
50
45
40
35
Major problem
Minor problem
No problem
30
25
20
15
10
5
0
Karlstad University
Dept. of Computer Science
Semla 10
Traceability of Errors
•
Where do delivered “bugs” come from?
Defect origins
Delivered defects (%)
Requirements
34
Design
26
Documentation
14
Bad fixes
14
Coding
12
Karlstad University
Dept. of Computer Science
Semla 11
Part 2
How to define a module with contracts
Karlstad University
Dept. of Computer Science
2000-05-09
Improved software quality through
semantic descriptions (Skutt)
Modularity
•
•
•
•
Modularity promotes black box design
The interface of each module should be well defined
– Syntactic definition
• Syntax = what the program looks like
– Semantic definition
• Semantics = what the program does
– We will use contracts for the semantic description
• Will be explained shortly
Each module should be used correctly
– The compiler helps us with the syntactic side
– We must take care of the semantic side ourselves
– Contracts will help us to use modules correctly
Each module should behave well
– The contracts will guide us to implement the correct semantics
Karlstad University
Dept. of Computer Science
Semla 13
Course Examples
•
We will look at two trivial examples to
illustrate and discuss contracts
•
A stack
– The operation top should return the
topmost element of the stack
•
A list
– The operation getElement should return
the selected element from the list
Karlstad University
Dept. of Computer Science
Semla 14
Contracts - Clients and Suppliers
•
A contract is an agreement between two parties
•
A contract has a client and a supplier
Karlstad University
Dept. of Computer Science
Semla 15
Contracts - Allocation of Responsibilities
•
•
A contract specifies obligations and benefits
Obligation
Benefit
Client
Pay
Get goods
Supplier
Supply goods
Get money
The supplier only needs to fulfill his obligations if the client fulfills his
Karlstad University
Dept. of Computer Science
Semla 16
Contracts - Preconditions and Postconditions
•
In module design, the obligations and benefits of the contracts are
regulated through preconditions and postconditions
Client
Supplier
Obligation:
•
Assure
precondition
Precondition
Method
Benefit:
•
Benefit:
•
Assume
postcondition
Karlstad University
Dept. of Computer Science
Assume
precondition
Obligation:
Postcondition
Semla 17
•
Assure
postcondition
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
Karlstad University
Dept. of Computer Science
Semla 18
Example 2.1
•
The following is one possible implementation of the operation top:
Object top() throws IndexOutOfBoundsException
{
if (size() > 0)
return elements[topIndex];
else
throw(new IndexOutOfBoundsException());
}
•
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?
Karlstad University
Dept. of Computer Science
Semla 19
Suggested Answer to Example 2.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:
– The stack is unchanged
– 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
Karlstad University
Dept. of Computer Science
Semla 20
Suggested Answer to Example 2.1, part 2
•
Another contract for top could be
•
Precondition:
– The stack is not empty
•
Postcondition:
– The stack is unchanged
– The topmost element of the stack is returned
Karlstad University
Dept. of Computer Science
Semla 21
Discussion around the Contracts
•
•
•
It will never be possible to get an element where there is
none
– Asking for the topmost element of an empty stack seems quite
meaningless
Imagine that you need a plate for your food. You know where
the plates use to be piled up
– Will you try to grasp one if the pile is empty?
– Probably, you first look to see if there is any plate left, and
then you pick one.
– If the pile is empty, you will probably look elsewhere for a plate
Does the same logic apply for software development?
– First make sure that an operation is meaningful
– Then do the operation
Karlstad University
Dept. of Computer Science
Semla 22
Comparing the Contracts
•
With the first contract, the responsibility for the dangerous situation
(an empty stack) is not clearly defined
– The stack is responsible for detecting an illegal call
– The client is responsible for handling the illegal call
– Code for handling the illegal situation is needed both in the client code
and in the stack module
– In the end, the client is still responsible for taking care of the situation
•
With the second contract, the stack knows that top will only be
invoked when it is meaningful
– The responsibility to assure that the call is meaningful is clearly
defined to be with the client
– The top method does not need to consider any other situation
Karlstad University
Dept. of Computer Science
Semla 23
Group Exercise 2.2
•
•
•
The list operation getElement(int position) should return the
element at the given position of a list
Define a suitable contract for this method
Discuss the consequences of your contract for the client and for the
supplier?
Karlstad University
Dept. of Computer Science
Semla 24
Group exercise 2.3
A moment of reflection:
???
?
What are Contracts Good for?
???
generate more
paperwork?
Look in appendix A for some ideas
Karlstad University
Dept. of Computer Science
Semla 25
Part 3
How to Use a Module Defined with Contracts
Karlstad University
Dept. of Computer Science
2000-05-09
Improved software quality through
semantic descriptions (Skutt)
How do the Users of a Module Benefit from Contracts?
•
The contracts makes it easier to understand the module
– The intentions of the module are described
– Ambiguities are removed
•
The distribution of responsibility is clear
– The user knows what is taken care of by the module and what is not
•
The users of a module knows what the module has done since this is
expressed in the postcondition
– No need to read the code in order to understand what the module has
done.
– The code can more easily be distributed in an interface part and an
implementation part since the users do not need to read the code.
Karlstad University
Dept. of Computer Science
Semla 27
Different Styles of Calling a Function With and Without
Contracts
•
Obtaining the top element of a stack
– with contracts
Precondition for top: !isEmpty()
•
User code
...pushes and pops...
if(!myStack.isEmpty())
anElement = myStack.top()
else
printErrorMessage();
Karlstad University
Dept. of Computer Science
Semla 28
Different Styles of Calling a Function With and Without
Contracts
•
Obtaining the top element of a stack
– without contracts
Precondition for top: true
•
User Code
...pushes and pops...
try {
anElement = myStack.top();
}
catch(stackEmptyException sEE)
{
printErrorMessage();
}
Karlstad University
Dept. of Computer Science
Semla 29
Discussion - Consequences for the user
•
As can be seen in the previous two examples, the user has to
perform a check both when using contracts and when not.
– The reason for this is of course that it is not known in advance if the
stack is empty or not and this is a situation that needs to be tested.
– In the contract example, the test comes before the call
– In the non-contract example, the test comes after the call
– The user must always test
Karlstad University
Dept. of Computer Science
Semla 30
Discussion - Weak and Strong Contracts
•
Contract use is more closely related to human thinking
– We tend to test before we do things. (At least most of us…)
– The pile of plates example shown previously is a typical example. We
don’t try to take something that isn’t there. We check first.
•
Even if no contracts are defined explicitly, they are present in the
way the method is being implemented
– Weak contract, e.g. precondition: true
– Strong contract, e.g. precondition: <a condition that the user must
ensure is true>
Karlstad University
Dept. of Computer Science
Semla 31
Discussion - Strong Contracts do not always Apply
•
It is not possible to use strong contracts in all cases
•
System boundary classes need weak contracts
– Communication over a non-reliable channel
• The channel might be working when the test is performed but nonworking when the call is to be executed.
– The user might not be trustable
• End-users do not accept that they have to test before a function
call, which calls for weak contracts.
•
Expensive or time-consuming tests may need weak contracts
– The test might include the completion of the actual call up to a certain
point, e.g. matrix inversion.
Karlstad University
Dept. of Computer Science
Semla 32
Part 4
How to Implement a Module Defined with Contracts
Karlstad University
Dept. of Computer Science
2000-05-09
Improved software quality through
semantic descriptions (Skutt)
How do the Programmers of a Module Benefit from
Contracts?
•
A contract specifies the precondition for the call
– Defines that the the client is responsible for the entrance conditions
– The supplier knows that this is not his responsibility
•
The supplier does not need to check a precondition
– It should always be true
– It would be a violation to the contract not to trust it
•
The supplier programmer can focus on solving the task defined for
the function
– He does not need to spend time and energy to catch “illegal” cases
– His code gets simpler and contains less errors
Karlstad University
Dept. of Computer Science
Semla 34
Different Programming Styles With and Without Contracts
•
Stack without contract
Object top() throws IndexOutOfBoundsException
{
if (size() >= 0)
return elements[topIndex];
else
throw(new IndexOutOfBoundsException());
}
•
Stack with contract
Object top()
{
return elements[topIndex];
}
Karlstad University
Dept. of Computer Science
Semla 35
Discussion
•
The solution without contract has more than twice as many program
lines as the one with contract
– Should be assumed to contain at least twice as many errors
•
In reality, the number of errors should be even greater, because of
the increased complexity
– The tests to detect illegal situations complicate the control structure of
the implementation
•
This may not be so serious for one single method
– With thousands of lines of code, it becomes a serious complication
•
Simplicity is the road to quality
– Every test complicates the program
Karlstad University
Dept. of Computer Science
Semla 36
Exercise 4.1: Implement getElement for a List
•
Assume that the list is implemented using an array of Objects
– Declared as Object[] stackArray = new Object[MaxSize]
•
Implement the contract from Exercise 2.2
– getElement(int position) should return the element at the
given position of a list
•
Precondition:
– Informally: position is ok.
– More formally: 0 < position && position <= listSize()
•
Postcondition:
– The element at the given position is returned
Karlstad University
Dept. of Computer Science
Semla 37
Exercise 4.2: 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
List
first
Node
next
Node
next
Repeat exercise 4.1 for this data
structure
– The data element at the selected
position should be returned
Karlstad University
Dept. of Computer Science
Semla 38
Object
Object
Course Summary
The Central Concepts from the Course
Karlstad University
Dept. of Computer Science
2000-05-09
Improved software quality through
semantic descriptions (Skutt)
What are Contracts Good for?
1 Design support tool
– This is the most important benefit from contracts
2 Documentation tool
– The contracts for a module describe the module
3 Error detection tool
– Requires language support
– Discussed in Appendix C
Karlstad University
Dept. of Computer Science
Semla 40
The Interpretation of a Contract
•
A contract consists of a precondition and a postcondition
•
When a method is invoked, the precondition should be true
– This is the responsibility of the client
– The supplier can assume that it is true
•
When a method exist, the postcondition should be true
– This is the responsibility of the supplier
• Only necessary if the precondition was true
– The client can assume that it is true
• Only guaranteed if the precondition was true
Karlstad University
Dept. of Computer Science
Semla 41
Paradox: Guaranteeing More by Checking Less
•
•
•
•
How can quality increase by less testing?
– Simplicity is the allied number one for quality
Placing conditions on the client allows for a simple implementation
– Hence allows for quality
Not trusting the client requires testing the conditions
– Both client and supplier need to test
– Hence complicating the implementation
– Hence jeopardizing the quality
The key issue is who’s “quality” we are looking for
– Microscopic view, just my own module:
• Lots of tests in the supplier code
– Macroscopic view, the system as a whole:
• Place the responsibility where it belongs
Karlstad University
Dept. of Computer Science
Semla 42
Applying a contract
•
When invoking a method
– Satisfy the precondition for all methods called.
– If the precondition was satisfied, then trust the postcondition.
•
When implementing a method
– Do not test conditions that are already satisfied according to the
precondition
– Make sure that the postcondition is satisfied before the method
terminates
Karlstad University
Dept. of Computer Science
Semla 43
Appendix A
Suggested answers to the exercises
Karlstad University
Dept. of Computer Science
2000-05-09
Improved software quality through
semantic descriptions (Skutt)
Suggested Solution to Group Exercise 2.2
Object getElement(int position)
• Precondition:
– Informally: position is ok.
– More formally: 0 < position && position <= listSize()
• Postcondition
– The element at the given position is returned
Karlstad University
Dept. of Computer Science
Semla 45
Suggested solution to Group Exercise 2.3
What are Contracts Good for?
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
Karlstad University
Dept. of Computer Science
Semla 46
Suggested solution to Exercise 4.1
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
Karlstad University
Dept. of Computer Science
Semla 47
Suggested solution to Exercise 4.2
public Object getElement(int position)
{
Node temp = first;
int i;
for(i = 1; i < position; i++)
temp = temp.getNext();
// termination guaranteed by pre
return temp.getData();
} // getElement
Karlstad University
Dept. of Computer Science
Semla 48
Appendix B
Application Exercise - Call Forward Service
Karlstad University
Dept. of Computer Science
2000-05-09
Improved software quality through
semantic descriptions (Skutt)
A Description of a Number Translation Service
•
The following picture shows a number translation feature being
called from a service session component
•
The service is a call forward service
•
The feature is a number translation feature
•
The method called is translate
– Indicated by the number 2 in the figure
•
Define the contract for the method
– Two scenarios are specified after the picture
Karlstad University
Dept. of Computer Science
Semla 50
The Description of a Number Translation Service
Feature session
component
Feature persistent
component
3) translate
Service session
component
2) translate
1) IDP
4) CON
Switching Network
Karlstad University
Dept. of Computer Science
Semla 51
Possible Scenarios
•
Scenario #1
– Both the A-number and the B-number are on the right format
– The B-number is known to exist in the database
•
Scenario #2
– Both the A-number and the B-number are on the right format
– B-number might not exist in the database
Karlstad University
Dept. of Computer Science
Semla 52
Appendix C
What Happens if the Precondition is not Satisfied?
Karlstad University
Dept. of Computer Science
2000-05-09
Improved software quality through
semantic descriptions (Skutt)
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 strategies are recommended
– Do nothing special
• try to perform the task
• hope that the system will die
– Trap the violation and make the system die
• throw a runtime exception or exit
• possibly dump an error code to a log file
Karlstad University
Dept. of Computer Science
Semla 54
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.
– The solution 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];
}
Karlstad University
Dept. of Computer Science
Semla 55
Do Not Try to Handle the Error
•
•
Handling errors by allowing the system to go on as if nothing
happens only makes things worse
– The client should not be aware of any exceptions that might be thrown
– It could be tempting to catch it and thereby to allow the error to live on
– Would actually implement a different contract than the one specified
for the method
Very different from error handling with weak contracts
– The client is not aware of the test
• from the client’s point of view, the contract is not “protected”
– The test can be removed without affecting the contract
• 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
Karlstad University
Dept. of Computer Science
Semla 56
Rules for Precondition Violation Traps
•
The trap should be completely transparent to the user
– There is 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 without a trap as
with it
– The program may be run with traps disabled
– The trap should not affect the behavior of the system in any way
– In particular, the trap should not change any variables
Karlstad University
Dept. of Computer Science
Semla 57
Addition to What are Contracts Good for?
1 Design support tool
– This is the most important benefit from contracts
– See Exercise 2.3 and Appendix A
2 Documentation tool
– The contracts for a module specify the requirements on the module
– See Exercise 2.3 and Appendix A
3 Error detection tool
– The contracts specify the conditions to test in order to trap errors
• Especially in preconditions
– Only apply to executable conditions
– Requires language support
All errors cannot be detected by a tool, but 1 and 2 always apply.
Karlstad University
Dept. of Computer Science
Semla 58