SlideShare ist ein Scribd-Unternehmen logo
1 von 3
Downloaden Sie, um offline zu lesen
T
HE LAST COLUMN EXPLORED REQUIREMENTS
under three headings[1]
: functional
requirements, which are automatically
testable and are concerned with purpose;
operational requirements, which focus on qualities
of service and use; and developmental requirements,
which are about qualities of implementation. The
last two categories are more specific than the
common but vague term, non-functional.
At the level of individual, fine-grained software
elements, such specifications are more commonly
phrased as contracts [2, 3]
rather than requirements.
The contract for something like an operation of
a class describes an agreement between the class user
and its designer. A contract contains requirements
that define the operation’s correct use and expected
outcomes. So, what does it take to draft such a
contract?
Sorting provides us with an example that is an
apparently simple but sufficiently deep example of
contract negotiation. Sorting algorithms appear
wrapped up in almost any standard library and
introductory computer science course. For this
reason, many programmers think that there is
nothing more to learn and that such examples
are too trivial to be of any use in larger systems.
However, it turns out that designing the contract
for a sorting operation embraces subtlety enough
to avoid any trivial pursuit.
Signature contracts
Sorting is not, generally speaking, the method of
any particular collection type. In Java, such an
orthogonal capability is normally expressed as a
static method in a mini-package-like class. C++
supports the slightly more natural expression of
such capabilities as global functions. For the
purpose of exploring sorting, C++ has the edge
because of its support for generic programming,
which is more naturally suited to expressing
algorithms.
TakingaleafstraightoutoftheC++standardlibrary,
the following declaration introduces our sorting
operation:
template<typename iterator>
void sort(iterator begin, iterator end);
Types are clearly contracts: they define what is
expected between the calling and called code; any
transgression of the contract invalidates the claim
to correctly executing code. Contract enforcement
may be eager, relaxed or apathetic: a statically
checked type system ensures conformance to an
expected type at compile time, which is the normal
model of use in C++ and Java; a dynamically
checked type system, as found in scripting languages
such as Python and Ruby or accessible in Java via
reflection, instead raises any alarm bells at runtime;
an unchecked type system, such as going via void
* in C or C++, just promises the obscurity and
unnecessary excitement of undefined behaviour if
the terms of the contract are not met.
For C++ template parameters the notion of
type is defined by how the type may be used
rather than in terms of a declared type, such as a
class. The iterator type of sort’s begin and end
arguments should follow STL idioms: iterators
should support pointer-like syntax.To be more precise,
the iterators should be random-access iterators, so
that they can refer to any element of their sequence
in constant time. This means that it takes as long
to lookup begin[0] as it does to lookup any valid
begin[i].
A further requirement is that the value type
referred to in the iterator range should support copying
and a strict ordering based on the conventional less-
than operator, <. For Java the copying requirement
q A contract is effectively an agreement
on the requirements fulfilled by a
component between the user of the
component and its supplier.
q Signature contracts specify the name,
arguments and related types for a
component.
q Functional contracts focus on the
effects of an operation,and are often
expressed in terms of pre- and
postconditions.
q Operational contracts address the
quality of service characteristics for a
component.
FACTS AT A GLANCE
PROGRAMMER’S WORKSHOP
What does it take to specify the interface to a software component?
Kevlin Henney negotiates programming by contract
Sorted
42 APPLICATION DEVELOPMENT ADVISOR q www.appdevadvisor.co.uk
JULY–AUGUST 2003 43
would make no sense, because it supports only reference semantics
and no value semantics, and the idiomatic turn of phrase for expressing
a strict ordering is to implement the compareTo method of the core
language Comparable interface because operator overloading is not
supported.
Functional contracts
The conventional view of design by contract [3,4]
is restricted to
functional constraints. Such contracts tend to be assertive in
nature: they are most commonly framed in terms of operation pre-
and postconditions. A precondition needs to be true on entry to
an operation, whether a method or a global function, and a
postcondition needs to be true on successful return.
The only meaningful precondition for sort is that begin and
end refer to elements in the same range. However, note that even
though the condition is not readily checkable, it is still a valid constraint
on the execution of the function: if the iterators are not in the same
range, the caller cannot expect a sensible outcome.
As for the postcondition, it would be easy to think that we’re almost
done: all the elements in the range must be sorted! However,
thatisnotquiteenough.First,whatdoesitmeantobesorted?Expressed
as generic predicate, a first stab might look like the following:
template<typename const_iterator>
bool is_sorted(const_iterator begin, const_iterator end)
{
const_iterator previous;
do
{
previous = begin++;
}
while(begin != end && *previous < *begin);
return begin == end;
}
One problem with this is that it fails for empty sequences, which
are, by definition, already sorted. Another more general problem
is that it does not allow successive elements to be equal: they must
ascend or be damned. So the correct definition of being sorted is
that each successive element must not be less than the previous
one, and both empty and single-item sequences are sorted by
definition:
template<typename const_iterator>
bool is_sorted(const_iterator begin, const_iterator end)
{
if(begin != end)
{
const_iterator previous;
do
{
previous = begin++;
}
while(begin != end && !(*begin < *previous));
}
return begin == end;
}
OK, that’s being sorted sorted, but the contract is still incomplete.
Consider the following pathological implementation:
template<typename iterator>
void sort(iterator begin, iterator end)
{
for(iterator source = begin; begin != end; ++begin)
*begin = *source;
}
This sets all of the elements in the range to have the same value
as the initial element. Is it sorted? Most definitely. Is it what we
expected? Most definitely not! So, being sorted is not enough: the
resulting sequence of values must be a permutation of the
original, i.e. it should contain the same values. A sorting algorithm
that pursues its own wayward agenda or that loses a value here
or there is of little use to anyone.
Operational contracts
Functional contracts are things that in principle you might want
to check by assertion, using the respective assert mechanism in C++
or Java, but that in practice you may not. Even when they can be
expressed in code, pre- and postcondition checking can have
profoundly undesirable effects on performance. You may be
thinking that it’s always OK to have assertions in a debug build because
optimisation is not a consideration, but reconsider: a typical
implementation of is_permutation that uses no additional memory
for intermediate data structures is going to perform up to O(N2
)
comparisons, where N is the length of the sequence to be sorted
and the O notation[6]
indicates the order at which the execution time
will change as N increases.
To get a feel for why the complexity of
<code>is_permutation</code> would O(N2
), consider how you
would compare the before and after snapshots of the sequence.
The good news is that the sequence after the call is sorted so you
can progress through it with the full knowledge that the values
are in ascending order, and identical values will be adjacent. The
bad news is that the sequence before the call is not necessarily sorted,
which means that you will generally need a linear search to find
the occurrence or recurrences of a value. So, in the worst case, to
confirm that for N sorted elements you have the same elements
you will have to search N unsorted elements O(N) times, which
gives you O(N2
).
Quadratic complexity means that performing the permutation
checkon1000elementswillbe100timesslowerthanfor100elements.
That’s not the kind of debug version you want to have produced
as the default development build. The proper way to check such
functional contracts is through testing rather than through
debugging [5]
. Instead of using the general assertion that the result
must be sorted and a permutation of the original, test specific input
data scenarios against their expected outcomes.
Just as it would be unreasonable to impose a quadratic overhead
in the check, it is perhaps equally unreasonable for the body of the
sortingoperationtocostO(N2
)oraboveforNrandom-accesselements.
Quadratic is the complexity of the infamous bubble sort, as well
as its slightly more compact and presentable cousin, selection
sort:
template<typename iterator>
void sort(iterator begin, iterator end)
{
for(; begin != end; ++begin)
std::swap(*begin, *std::min_element(begin, end));
}
Short and sweet, but still quadratic. If such complexity is a little
PROGRAMMER’S WORKSHOP
unreasonable, the following is intolerably unreasonable:
template<typename iterator>
void sort(iterator begin, iterator end)
{
while(std::prev_permutation(begin, end))
;
}
This implementation iterates through the permutations of the
sequence. Each permutation is successively more sorted than the
previous one, until the sequence is fully sorted and prev_permutation
returns false. Very cute. Very, very, very slow. It is combinatorially
slow, with a worst-case scenario that bites like a vampire: a
sequence of 5 elements could take up to 120 iterations to sort;
a sequence of 10 elements could take up to nearly 4 million.
The performance complexity of the implementation is not merely
an “implementation detail”: it should be subject to contract. How
can you meaningfully program to an interface if you have to find
out the implementation to make reasonable use of it?
The C standard library’s qsort function has both a type-
dangerous, void * based interface and a complete absence of
performance guarantee. Although it is probably safe to assume
that library authors would not go out of their way to create a poor
implementation, the absence of any guarantee means that you cannot
know whether a space or a time trade off is made in its
implementation. C++’s stable_sort and Java’s Collections.sort
use additional memory to get their best performance. Other sorting
algorithms sort in place, and do not therefore hit the heap.
Swings and roundabouts — it’s worth knowing which one you
are on.
Without actually specifying an implementation, it is reasonable
to stipulate an O(N log N) requirement for the average performance
complexity of sort, a contract that can be fulfilled by quicksort,
its variants and a number of other algorithms. Additionally, we
can specify that sorting occurs in place, without demanding
additional heap memory, and that in the event of an exception
during sorting the sequence is left in a valid, albeit unspecified,
state. s
References
1. Kevlin Henney, “Inside requirements”, Application
Development Advisor, May–June 2003.
2. Butler W Lampson, “Hints for computer system design”,
Operating Systems Review, October 1983
http://research.microsoft.com/~lampson/33-Hints/
WebPage.html
3. Bertrand Meyer, Object-Oriented Software Construction, 2nd
edition, Prentice Hall, 1997.
4. Andrew Hunt and David Thomas, The Pragmatic
Programmer, Addison-Wesley, 2000.
5. Kevlin Henney, “Put to the test”, Application Development
Advisor, November–December 2002.
6. Brian W Kernighan and Rob Pike, The Practice of
Programming, Addison-Wesley, 1999.
PROGRAMMER’S WORKSHOP

Weitere ähnliche Inhalte

Was ist angesagt?

Refactoring for Software Design Smells
Refactoring for Software Design SmellsRefactoring for Software Design Smells
Refactoring for Software Design SmellsGanesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Solid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile developmentSolid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile developmentSimon Gould
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. David Gómez García
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software DevelopmentAndré Pitombeira
 
Something for Nothing
Something for NothingSomething for Nothing
Something for NothingKevlin Henney
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 
2015.01.09 - Writing Modern Applications for Mobile and Web
2015.01.09 - Writing Modern Applications for Mobile and Web2015.01.09 - Writing Modern Applications for Mobile and Web
2015.01.09 - Writing Modern Applications for Mobile and WebMarco Parenzan
 
Writing High Quality Code in C#
Writing High Quality Code in C#Writing High Quality Code in C#
Writing High Quality Code in C#Svetlin Nakov
 
TDD Walkthrough - Encryption
TDD Walkthrough - EncryptionTDD Walkthrough - Encryption
TDD Walkthrough - EncryptionPeterKha2
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeyCefalo
 
WordCamp US: Clean Code
WordCamp US: Clean CodeWordCamp US: Clean Code
WordCamp US: Clean Codemtoppa
 
Design for Testability
Design for Testability Design for Testability
Design for Testability Pawel Kalbrun
 
A Survey Of Agile Development Methodologies
A Survey Of Agile Development MethodologiesA Survey Of Agile Development Methodologies
A Survey Of Agile Development MethodologiesAbdul Basit
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_pptagnes_crepet
 

Was ist angesagt? (20)

Refactoring for Software Design Smells
Refactoring for Software Design SmellsRefactoring for Software Design Smells
Refactoring for Software Design Smells
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Solid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile developmentSolid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile development
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min.
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software Development
 
Clean Code V2
Clean Code V2Clean Code V2
Clean Code V2
 
Something for Nothing
Something for NothingSomething for Nothing
Something for Nothing
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
2015.01.09 - Writing Modern Applications for Mobile and Web
2015.01.09 - Writing Modern Applications for Mobile and Web2015.01.09 - Writing Modern Applications for Mobile and Web
2015.01.09 - Writing Modern Applications for Mobile and Web
 
Thoughtful Software Design
Thoughtful Software DesignThoughtful Software Design
Thoughtful Software Design
 
Clean code-v2.2
Clean code-v2.2Clean code-v2.2
Clean code-v2.2
 
Writing High Quality Code in C#
Writing High Quality Code in C#Writing High Quality Code in C#
Writing High Quality Code in C#
 
TDD Walkthrough - Encryption
TDD Walkthrough - EncryptionTDD Walkthrough - Encryption
TDD Walkthrough - Encryption
 
BDD Primer
BDD PrimerBDD Primer
BDD Primer
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit Dey
 
WordCamp US: Clean Code
WordCamp US: Clean CodeWordCamp US: Clean Code
WordCamp US: Clean Code
 
Design for Testability
Design for Testability Design for Testability
Design for Testability
 
A Survey Of Agile Development Methodologies
A Survey Of Agile Development MethodologiesA Survey Of Agile Development Methodologies
A Survey Of Agile Development Methodologies
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_ppt
 

Andere mochten auch

Dia mundial del no el tabaco
Dia mundial del  no el tabacoDia mundial del  no el tabaco
Dia mundial del no el tabacogalojairo
 
Principales variables e indicadores para evaluar sistemas educativos
Principales variables e indicadores para evaluar sistemas educativosPrincipales variables e indicadores para evaluar sistemas educativos
Principales variables e indicadores para evaluar sistemas educativosvirgen manuela ortiz c
 
《莲花海》(6) 智慧的修行方向(6)-今生的资源组合与命运的关系-「钱」从何来?-历史重演-措手不及的打击-究竟是什么道理?-传法的准则-自救的智慧-啤...
《莲花海》(6) 智慧的修行方向(6)-今生的资源组合与命运的关系-「钱」从何来?-历史重演-措手不及的打击-究竟是什么道理?-传法的准则-自救的智慧-啤...《莲花海》(6) 智慧的修行方向(6)-今生的资源组合与命运的关系-「钱」从何来?-历史重演-措手不及的打击-究竟是什么道理?-传法的准则-自救的智慧-啤...
《莲花海》(6) 智慧的修行方向(6)-今生的资源组合与命运的关系-「钱」从何来?-历史重演-措手不及的打击-究竟是什么道理?-传法的准则-自救的智慧-啤...DudjomBuddhistAssociation
 
Web2.0: Integration issues
Web2.0: Integration issuesWeb2.0: Integration issues
Web2.0: Integration issueshnzz pronk
 
Harry - Task 3 Evalutaion
Harry - Task 3 EvalutaionHarry - Task 3 Evalutaion
Harry - Task 3 EvalutaionHazzaDavies
 
Yucan - The InsideOut Methodology
Yucan - The InsideOut MethodologyYucan - The InsideOut Methodology
Yucan - The InsideOut Methodologyyucan-it
 
India Dew Journal April 2015SR
India Dew Journal April 2015SRIndia Dew Journal April 2015SR
India Dew Journal April 2015SRScott Rettberg
 
LandCity Revolution 2016 - La trasformazione dei territori in Smart Land - Be...
LandCity Revolution 2016 - La trasformazione dei territori in Smart Land - Be...LandCity Revolution 2016 - La trasformazione dei territori in Smart Land - Be...
LandCity Revolution 2016 - La trasformazione dei territori in Smart Land - Be...giovanni biallo
 
Práctica con Gimp: Ayuntamiento
Práctica con Gimp: AyuntamientoPráctica con Gimp: Ayuntamiento
Práctica con Gimp: Ayuntamientoauladetecnologias
 
Relación de la Agricultura y Nutricion
Relación de la Agricultura y NutricionRelación de la Agricultura y Nutricion
Relación de la Agricultura y NutricionAnibal_Lechon
 
Mercado de negocios. mercadotecnia
Mercado de negocios. mercadotecniaMercado de negocios. mercadotecnia
Mercado de negocios. mercadotecniaLisa_Pera
 
Orient textiles 3 piece chiffon collection 2016
Orient textiles 3 piece chiffon collection 2016Orient textiles 3 piece chiffon collection 2016
Orient textiles 3 piece chiffon collection 2016Orient Textiles
 
NEC's Lithium Ion battery for EVs to TelecomTower
NEC's Lithium Ion battery for EVs to TelecomTowerNEC's Lithium Ion battery for EVs to TelecomTower
NEC's Lithium Ion battery for EVs to TelecomTowerPrernasinghrawat
 

Andere mochten auch (20)

Dia mundial del no el tabaco
Dia mundial del  no el tabacoDia mundial del  no el tabaco
Dia mundial del no el tabaco
 
Principales variables e indicadores para evaluar sistemas educativos
Principales variables e indicadores para evaluar sistemas educativosPrincipales variables e indicadores para evaluar sistemas educativos
Principales variables e indicadores para evaluar sistemas educativos
 
Test
TestTest
Test
 
《莲花海》(6) 智慧的修行方向(6)-今生的资源组合与命运的关系-「钱」从何来?-历史重演-措手不及的打击-究竟是什么道理?-传法的准则-自救的智慧-啤...
《莲花海》(6) 智慧的修行方向(6)-今生的资源组合与命运的关系-「钱」从何来?-历史重演-措手不及的打击-究竟是什么道理?-传法的准则-自救的智慧-啤...《莲花海》(6) 智慧的修行方向(6)-今生的资源组合与命运的关系-「钱」从何来?-历史重演-措手不及的打击-究竟是什么道理?-传法的准则-自救的智慧-啤...
《莲花海》(6) 智慧的修行方向(6)-今生的资源组合与命运的关系-「钱」从何来?-历史重演-措手不及的打击-究竟是什么道理?-传法的准则-自救的智慧-啤...
 
NTIC´S
NTIC´S NTIC´S
NTIC´S
 
Web2.0: Integration issues
Web2.0: Integration issuesWeb2.0: Integration issues
Web2.0: Integration issues
 
Arqueologia
ArqueologiaArqueologia
Arqueologia
 
MANGAL JANI .
MANGAL JANI .MANGAL JANI .
MANGAL JANI .
 
Harry - Task 3 Evalutaion
Harry - Task 3 EvalutaionHarry - Task 3 Evalutaion
Harry - Task 3 Evalutaion
 
Yucan - The InsideOut Methodology
Yucan - The InsideOut MethodologyYucan - The InsideOut Methodology
Yucan - The InsideOut Methodology
 
India Dew Journal April 2015SR
India Dew Journal April 2015SRIndia Dew Journal April 2015SR
India Dew Journal April 2015SR
 
LandCity Revolution 2016 - La trasformazione dei territori in Smart Land - Be...
LandCity Revolution 2016 - La trasformazione dei territori in Smart Land - Be...LandCity Revolution 2016 - La trasformazione dei territori in Smart Land - Be...
LandCity Revolution 2016 - La trasformazione dei territori in Smart Land - Be...
 
iva 0 - 12 % agente de retenciones
iva 0 - 12 % agente de retenciones iva 0 - 12 % agente de retenciones
iva 0 - 12 % agente de retenciones
 
Práctica con Gimp: Ayuntamiento
Práctica con Gimp: AyuntamientoPráctica con Gimp: Ayuntamiento
Práctica con Gimp: Ayuntamiento
 
Relación de la Agricultura y Nutricion
Relación de la Agricultura y NutricionRelación de la Agricultura y Nutricion
Relación de la Agricultura y Nutricion
 
LA MEIOSI
LA MEIOSILA MEIOSI
LA MEIOSI
 
Mercado de negocios. mercadotecnia
Mercado de negocios. mercadotecniaMercado de negocios. mercadotecnia
Mercado de negocios. mercadotecnia
 
Orient textiles 3 piece chiffon collection 2016
Orient textiles 3 piece chiffon collection 2016Orient textiles 3 piece chiffon collection 2016
Orient textiles 3 piece chiffon collection 2016
 
NEC's Lithium Ion battery for EVs to TelecomTower
NEC's Lithium Ion battery for EVs to TelecomTowerNEC's Lithium Ion battery for EVs to TelecomTower
NEC's Lithium Ion battery for EVs to TelecomTower
 
How to write a speech
How to write a speechHow to write a speech
How to write a speech
 

Ähnlich wie Sorted

Contracts in Ruby - Vladyslav Hesal
Contracts in Ruby - Vladyslav HesalContracts in Ruby - Vladyslav Hesal
Contracts in Ruby - Vladyslav HesalRuby Meditation
 
Introduction to Contracts and Functional Contracts
Introduction to Contracts and Functional ContractsIntroduction to Contracts and Functional Contracts
Introduction to Contracts and Functional ContractsDaniel Prager
 
A Verified Modern SAT Solver
A Verified Modern SAT SolverA Verified Modern SAT Solver
A Verified Modern SAT SolverKatie Naple
 
Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Concetto Labs
 
A Formal Executable Semantics Of Verilog
A Formal Executable Semantics Of VerilogA Formal Executable Semantics Of Verilog
A Formal Executable Semantics Of VerilogTracy Morgan
 
No Memory for Contracts
No Memory for ContractsNo Memory for Contracts
No Memory for ContractsKevlin Henney
 
Contract-oriented PLSQL Programming
Contract-oriented PLSQL ProgrammingContract-oriented PLSQL Programming
Contract-oriented PLSQL ProgrammingJohn Beresniewicz
 
why c++11?
why c++11?why c++11?
why c++11?idrajeev
 
Contract First Modeling Services Using Uml
Contract First Modeling Services Using UmlContract First Modeling Services Using Uml
Contract First Modeling Services Using UmlRody Middelkoop
 
Components in real time systems
Components in real time systemsComponents in real time systems
Components in real time systemsSaransh Garg
 
OOPSLA02 BehavioralSemantics.ppt
OOPSLA02 BehavioralSemantics.pptOOPSLA02 BehavioralSemantics.ppt
OOPSLA02 BehavioralSemantics.pptPtidej Team
 

Ähnlich wie Sorted (20)

Bound and Checked
Bound and CheckedBound and Checked
Bound and Checked
 
First Among Equals
First Among EqualsFirst Among Equals
First Among Equals
 
Contracts in Ruby - Vladyslav Hesal
Contracts in Ruby - Vladyslav HesalContracts in Ruby - Vladyslav Hesal
Contracts in Ruby - Vladyslav Hesal
 
Introduction to Contracts and Functional Contracts
Introduction to Contracts and Functional ContractsIntroduction to Contracts and Functional Contracts
Introduction to Contracts and Functional Contracts
 
Oopsla02 behavioralsemantics.ppt
Oopsla02 behavioralsemantics.pptOopsla02 behavioralsemantics.ppt
Oopsla02 behavioralsemantics.ppt
 
A Verified Modern SAT Solver
A Verified Modern SAT SolverA Verified Modern SAT Solver
A Verified Modern SAT Solver
 
Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...
 
A Formal Executable Semantics Of Verilog
A Formal Executable Semantics Of VerilogA Formal Executable Semantics Of Verilog
A Formal Executable Semantics Of Verilog
 
No Memory for Contracts
No Memory for ContractsNo Memory for Contracts
No Memory for Contracts
 
Contract-oriented PLSQL Programming
Contract-oriented PLSQL ProgrammingContract-oriented PLSQL Programming
Contract-oriented PLSQL Programming
 
why c++11?
why c++11?why c++11?
why c++11?
 
Contract First Modeling Services Using Uml
Contract First Modeling Services Using UmlContract First Modeling Services Using Uml
Contract First Modeling Services Using Uml
 
Unit 1
Unit  1Unit  1
Unit 1
 
Components in real time systems
Components in real time systemsComponents in real time systems
Components in real time systems
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
OOPSLA02 BehavioralSemantics.ppt
OOPSLA02 BehavioralSemantics.pptOOPSLA02 BehavioralSemantics.ppt
OOPSLA02 BehavioralSemantics.ppt
 
Survelaine murillo ppt
Survelaine murillo pptSurvelaine murillo ppt
Survelaine murillo ppt
 
Coverage and Introduction to UVM
Coverage and Introduction to UVMCoverage and Introduction to UVM
Coverage and Introduction to UVM
 
Put to the Test
Put to the TestPut to the Test
Put to the Test
 
Test design techniques
Test design techniquesTest design techniques
Test design techniques
 

Mehr von Kevlin Henney

The Case for Technical Excellence
The Case for Technical ExcellenceThe Case for Technical Excellence
The Case for Technical ExcellenceKevlin Henney
 
Empirical Development
Empirical DevelopmentEmpirical Development
Empirical DevelopmentKevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid DeconstructionKevlin Henney
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
 
Structure and Interpretation of Test Cases
Structure and Interpretation of Test CasesStructure and Interpretation of Test Cases
Structure and Interpretation of Test CasesKevlin Henney
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to ImmutabilityKevlin Henney
 
Turning Development Outside-In
Turning Development Outside-InTurning Development Outside-In
Turning Development Outside-InKevlin Henney
 
Giving Code a Good Name
Giving Code a Good NameGiving Code a Good Name
Giving Code a Good NameKevlin Henney
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Kevlin Henney
 
Thinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantThinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantKevlin Henney
 

Mehr von Kevlin Henney (20)

Program with GUTs
Program with GUTsProgram with GUTs
Program with GUTs
 
The Case for Technical Excellence
The Case for Technical ExcellenceThe Case for Technical Excellence
The Case for Technical Excellence
 
Empirical Development
Empirical DevelopmentEmpirical Development
Empirical Development
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid Deconstruction
 
Get Kata
Get KataGet Kata
Get Kata
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 
Structure and Interpretation of Test Cases
Structure and Interpretation of Test CasesStructure and Interpretation of Test Cases
Structure and Interpretation of Test Cases
 
Agility ≠ Speed
Agility ≠ SpeedAgility ≠ Speed
Agility ≠ Speed
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Old Is the New New
Old Is the New NewOld Is the New New
Old Is the New New
 
Turning Development Outside-In
Turning Development Outside-InTurning Development Outside-In
Turning Development Outside-In
 
Giving Code a Good Name
Giving Code a Good NameGiving Code a Good Name
Giving Code a Good Name
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
 
Thinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantThinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation Quadrant
 
Code as Risk
Code as RiskCode as Risk
Code as Risk
 
Software Is Details
Software Is DetailsSoftware Is Details
Software Is Details
 
Game of Sprints
Game of SprintsGame of Sprints
Game of Sprints
 
Good Code
Good CodeGood Code
Good Code
 

Kürzlich hochgeladen

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 

Kürzlich hochgeladen (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

Sorted

  • 1. T HE LAST COLUMN EXPLORED REQUIREMENTS under three headings[1] : functional requirements, which are automatically testable and are concerned with purpose; operational requirements, which focus on qualities of service and use; and developmental requirements, which are about qualities of implementation. The last two categories are more specific than the common but vague term, non-functional. At the level of individual, fine-grained software elements, such specifications are more commonly phrased as contracts [2, 3] rather than requirements. The contract for something like an operation of a class describes an agreement between the class user and its designer. A contract contains requirements that define the operation’s correct use and expected outcomes. So, what does it take to draft such a contract? Sorting provides us with an example that is an apparently simple but sufficiently deep example of contract negotiation. Sorting algorithms appear wrapped up in almost any standard library and introductory computer science course. For this reason, many programmers think that there is nothing more to learn and that such examples are too trivial to be of any use in larger systems. However, it turns out that designing the contract for a sorting operation embraces subtlety enough to avoid any trivial pursuit. Signature contracts Sorting is not, generally speaking, the method of any particular collection type. In Java, such an orthogonal capability is normally expressed as a static method in a mini-package-like class. C++ supports the slightly more natural expression of such capabilities as global functions. For the purpose of exploring sorting, C++ has the edge because of its support for generic programming, which is more naturally suited to expressing algorithms. TakingaleafstraightoutoftheC++standardlibrary, the following declaration introduces our sorting operation: template<typename iterator> void sort(iterator begin, iterator end); Types are clearly contracts: they define what is expected between the calling and called code; any transgression of the contract invalidates the claim to correctly executing code. Contract enforcement may be eager, relaxed or apathetic: a statically checked type system ensures conformance to an expected type at compile time, which is the normal model of use in C++ and Java; a dynamically checked type system, as found in scripting languages such as Python and Ruby or accessible in Java via reflection, instead raises any alarm bells at runtime; an unchecked type system, such as going via void * in C or C++, just promises the obscurity and unnecessary excitement of undefined behaviour if the terms of the contract are not met. For C++ template parameters the notion of type is defined by how the type may be used rather than in terms of a declared type, such as a class. The iterator type of sort’s begin and end arguments should follow STL idioms: iterators should support pointer-like syntax.To be more precise, the iterators should be random-access iterators, so that they can refer to any element of their sequence in constant time. This means that it takes as long to lookup begin[0] as it does to lookup any valid begin[i]. A further requirement is that the value type referred to in the iterator range should support copying and a strict ordering based on the conventional less- than operator, <. For Java the copying requirement q A contract is effectively an agreement on the requirements fulfilled by a component between the user of the component and its supplier. q Signature contracts specify the name, arguments and related types for a component. q Functional contracts focus on the effects of an operation,and are often expressed in terms of pre- and postconditions. q Operational contracts address the quality of service characteristics for a component. FACTS AT A GLANCE PROGRAMMER’S WORKSHOP What does it take to specify the interface to a software component? Kevlin Henney negotiates programming by contract Sorted 42 APPLICATION DEVELOPMENT ADVISOR q www.appdevadvisor.co.uk
  • 2. JULY–AUGUST 2003 43 would make no sense, because it supports only reference semantics and no value semantics, and the idiomatic turn of phrase for expressing a strict ordering is to implement the compareTo method of the core language Comparable interface because operator overloading is not supported. Functional contracts The conventional view of design by contract [3,4] is restricted to functional constraints. Such contracts tend to be assertive in nature: they are most commonly framed in terms of operation pre- and postconditions. A precondition needs to be true on entry to an operation, whether a method or a global function, and a postcondition needs to be true on successful return. The only meaningful precondition for sort is that begin and end refer to elements in the same range. However, note that even though the condition is not readily checkable, it is still a valid constraint on the execution of the function: if the iterators are not in the same range, the caller cannot expect a sensible outcome. As for the postcondition, it would be easy to think that we’re almost done: all the elements in the range must be sorted! However, thatisnotquiteenough.First,whatdoesitmeantobesorted?Expressed as generic predicate, a first stab might look like the following: template<typename const_iterator> bool is_sorted(const_iterator begin, const_iterator end) { const_iterator previous; do { previous = begin++; } while(begin != end && *previous < *begin); return begin == end; } One problem with this is that it fails for empty sequences, which are, by definition, already sorted. Another more general problem is that it does not allow successive elements to be equal: they must ascend or be damned. So the correct definition of being sorted is that each successive element must not be less than the previous one, and both empty and single-item sequences are sorted by definition: template<typename const_iterator> bool is_sorted(const_iterator begin, const_iterator end) { if(begin != end) { const_iterator previous; do { previous = begin++; } while(begin != end && !(*begin < *previous)); } return begin == end; } OK, that’s being sorted sorted, but the contract is still incomplete. Consider the following pathological implementation: template<typename iterator> void sort(iterator begin, iterator end) { for(iterator source = begin; begin != end; ++begin) *begin = *source; } This sets all of the elements in the range to have the same value as the initial element. Is it sorted? Most definitely. Is it what we expected? Most definitely not! So, being sorted is not enough: the resulting sequence of values must be a permutation of the original, i.e. it should contain the same values. A sorting algorithm that pursues its own wayward agenda or that loses a value here or there is of little use to anyone. Operational contracts Functional contracts are things that in principle you might want to check by assertion, using the respective assert mechanism in C++ or Java, but that in practice you may not. Even when they can be expressed in code, pre- and postcondition checking can have profoundly undesirable effects on performance. You may be thinking that it’s always OK to have assertions in a debug build because optimisation is not a consideration, but reconsider: a typical implementation of is_permutation that uses no additional memory for intermediate data structures is going to perform up to O(N2 ) comparisons, where N is the length of the sequence to be sorted and the O notation[6] indicates the order at which the execution time will change as N increases. To get a feel for why the complexity of <code>is_permutation</code> would O(N2 ), consider how you would compare the before and after snapshots of the sequence. The good news is that the sequence after the call is sorted so you can progress through it with the full knowledge that the values are in ascending order, and identical values will be adjacent. The bad news is that the sequence before the call is not necessarily sorted, which means that you will generally need a linear search to find the occurrence or recurrences of a value. So, in the worst case, to confirm that for N sorted elements you have the same elements you will have to search N unsorted elements O(N) times, which gives you O(N2 ). Quadratic complexity means that performing the permutation checkon1000elementswillbe100timesslowerthanfor100elements. That’s not the kind of debug version you want to have produced as the default development build. The proper way to check such functional contracts is through testing rather than through debugging [5] . Instead of using the general assertion that the result must be sorted and a permutation of the original, test specific input data scenarios against their expected outcomes. Just as it would be unreasonable to impose a quadratic overhead in the check, it is perhaps equally unreasonable for the body of the sortingoperationtocostO(N2 )oraboveforNrandom-accesselements. Quadratic is the complexity of the infamous bubble sort, as well as its slightly more compact and presentable cousin, selection sort: template<typename iterator> void sort(iterator begin, iterator end) { for(; begin != end; ++begin) std::swap(*begin, *std::min_element(begin, end)); } Short and sweet, but still quadratic. If such complexity is a little PROGRAMMER’S WORKSHOP
  • 3. unreasonable, the following is intolerably unreasonable: template<typename iterator> void sort(iterator begin, iterator end) { while(std::prev_permutation(begin, end)) ; } This implementation iterates through the permutations of the sequence. Each permutation is successively more sorted than the previous one, until the sequence is fully sorted and prev_permutation returns false. Very cute. Very, very, very slow. It is combinatorially slow, with a worst-case scenario that bites like a vampire: a sequence of 5 elements could take up to 120 iterations to sort; a sequence of 10 elements could take up to nearly 4 million. The performance complexity of the implementation is not merely an “implementation detail”: it should be subject to contract. How can you meaningfully program to an interface if you have to find out the implementation to make reasonable use of it? The C standard library’s qsort function has both a type- dangerous, void * based interface and a complete absence of performance guarantee. Although it is probably safe to assume that library authors would not go out of their way to create a poor implementation, the absence of any guarantee means that you cannot know whether a space or a time trade off is made in its implementation. C++’s stable_sort and Java’s Collections.sort use additional memory to get their best performance. Other sorting algorithms sort in place, and do not therefore hit the heap. Swings and roundabouts — it’s worth knowing which one you are on. Without actually specifying an implementation, it is reasonable to stipulate an O(N log N) requirement for the average performance complexity of sort, a contract that can be fulfilled by quicksort, its variants and a number of other algorithms. Additionally, we can specify that sorting occurs in place, without demanding additional heap memory, and that in the event of an exception during sorting the sequence is left in a valid, albeit unspecified, state. s References 1. Kevlin Henney, “Inside requirements”, Application Development Advisor, May–June 2003. 2. Butler W Lampson, “Hints for computer system design”, Operating Systems Review, October 1983 http://research.microsoft.com/~lampson/33-Hints/ WebPage.html 3. Bertrand Meyer, Object-Oriented Software Construction, 2nd edition, Prentice Hall, 1997. 4. Andrew Hunt and David Thomas, The Pragmatic Programmer, Addison-Wesley, 2000. 5. Kevlin Henney, “Put to the test”, Application Development Advisor, November–December 2002. 6. Brian W Kernighan and Rob Pike, The Practice of Programming, Addison-Wesley, 1999. PROGRAMMER’S WORKSHOP